【发布时间】:2013-04-14 11:16:22
【问题描述】:
我尝试在 WinForms .NET 4.0 上使用 TPL,我按照用于 WPF 的this 步骤(转到文章末尾)进行了一些小改动,以便它可以在 WinForms 上运行,但它仍然无法运行..它应该在标签和richTextBox上显示结果,但它不是......我认为并行过程工作会导致当我单击按钮时鼠标开始缓慢移动一段时间......
public static double SumRootN(int root)
{ double result = 0;
for (int i = 1; i < 10000000; i++)
{ result += Math.Exp(Math.Log(i) / root);}
return result;
}
private void button1_Click(object sender, EventArgs e)
{ richTextBox1.Text = "";
label1.Text = "Milliseconds: ";
var watch = Stopwatch.StartNew();
List<Task> tasks = new List<Task>();
for (int i = 2; i < 20; i++)
{ int j = i;
var t = Task.Factory.StartNew
( () =>
{ var result = SumRootN(j);
Dispatcher.CurrentDispatcher.BeginInvoke
(new Action
( () => richTextBox1.Text += "root " + j.ToString()
+ " " + result.ToString() + Environment.NewLine
)
, null
);
}
);
tasks.Add(t);
}
Task.Factory.ContinueWhenAll
( tasks.ToArray()
, result =>
{ var time = watch.ElapsedMilliseconds;
Dispatcher.CurrentDispatcher.BeginInvoke
( new Action
( () =>
label1.Text += time.ToString()
)
);
}
);
}
【问题讨论】:
-
Dispatcher 与 WPF 有关,您不应该在 winforms 中真正使用它。见stackoverflow.com/questions/303116/…
-
调度员is related to any thread in/to any application。 WPF 表单有
DispatcherObject提供对 UI 线程Dispatcher的访问
标签: c# wpf winforms task-parallel-library