C# · 3月 28, 2022

c# – 在WinForms上使用TPL进行并行编程

我试图在WinForms .NET 4.0上使用TPL,我按照 this步骤(转到文章的末尾)进行了WPF并进行了一些小改动,因此它可以在WinForms上运行,但它仍然不起作用..它应该显示标签和richText@R_833_2419@上的结果,但它不…我认为并行处理工作导致鼠标开始移动缓慢一段时间我点击按钮..

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){ richText@R_833_2419@1.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 ( () => richText@R_833_2419@1.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() ) ); } );}解决方法 您的代码将无法正常工作,因为显示结果的线程UI与WPF完全不同.
使用WPF,线程UI是Dispatcher,但在Windows Form上是另一个.

我修改了你的代码以帮助它工作.

private void button1_Click(object sender,EventArgs e) { richText@R_833_2419@1.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); richText@R_833_2419@1.Invoke(new Action( () => richText@R_833_2419@1.Text += “root ” + j.ToString() + ” ” + result.ToString() + Environment.NewLine)); }); tasks.Add(t); } Task.Factory.ContinueWhenAll(tasks.ToArray(),result => { var time = watch.ElapsedMilliseconds; label1.Invoke(new Action(() => label1.Text += time.ToString())); }); }