我试图实现的是在不同的线程中为集合中的每个值执行一个方法。我想测量完成所有任务所经过的时间。我的代码如下:
private ConcurrentQueue<string> Results { get; set; }
public System.Threading.Timer Updater { get; set; }
private Dictionary<int, string> Instances { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Instances = new Dictionary<int, string>();
this.Instances.Add(01, "A");
this.Instances.Add(02, "B");
this.Instances.Add(03, "C");
this.Instances.Add(04, "D");
this.Instances.Add(05, "E");
this.Instances.Add(06, "F");
this.Instances.Add(07, "G");
this.Instances.Add(08, "H");
this.Instances.Add(09, "I");
this.Instances.Add(10, "J");
this.Updater =
new System.Threading.Timer(new TimerCallback(Updater_CallBack), null, 0, 1000);
}
/// <summary>
///
/// </summary>
/// <param name="State"></param>
void Updater_CallBack(object State)
{
this.Operation();
}
private void Operation()
{
var Watcher = new System.Diagnostics.Stopwatch();
Watcher.Restart();
this.Results = new ConcurrentQueue<string>();
var Tasks = new System.Threading.Tasks.Task[this.Instances.Count];
int i = 0;
foreach (var Pair in this.Instances)
{
Tasks[i] = Task.Factory.StartNew(() => { this.Tasker(Pair.Value); });
i++;
}
System.Threading.Tasks.Task.WaitAll(Tasks);
Watcher.Stop();
var Text = new StringBuilder();
foreach (var Result in Results) Text.Append(Result);
System.IO.File.AppendAllText(@"D:\Tasks.TXT", Watcher.ElapsedMilliseconds.ToString() + " " + Text.ToString() + Environment.NewLine);
}
private void Tasker(string Id)
{
switch (Id)
{
case "A": Thread.Sleep(100); this.Results.Enqueue("a"); break;
case "B": Thread.Sleep(100); this.Results.Enqueue("b"); break;
case "C": Thread.Sleep(100); this.Results.Enqueue("c"); break;
case "D": Thread.Sleep(100); this.Results.Enqueue("d"); break;
case "E": Thread.Sleep(100); this.Results.Enqueue("e"); break;
case "F": Thread.Sleep(100); this.Results.Enqueue("f"); break;
case "G": Thread.Sleep(100); this.Results.Enqueue("g"); break;
case "H": Thread.Sleep(100); this.Results.Enqueue("h"); break;
case "I": Thread.Sleep(100); this.Results.Enqueue("i"); break;
case "J": Thread.Sleep(100); this.Results.Enqueue("j"); break;
}
}
我在这里期望的是 Tasker 方法执行 10 次,但每次执行不同的结果。当我查看我的结果时,我看到以下内容:
200 jjjjjjjjjj
101 jjjjjjgjjj
101 hhhhhhhhjj
101 hjjjjjjjjj
101 jjjjjjjjhj
100 jjjjjjjjjh
101 jjjjjjjjjj
Tasker 方法多次执行'j'。我无法弄清楚为什么不对集合中的其他字母执行该方法。我在这里想念什么?