我正在尝试在WinForms .NET 4.0上使用TPL,我按照此页面上的步骤(跳到文章末尾)进行操作,这些步骤适用于WPF,我做了一些小改动以便它可以在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()
)
);
}
);
}
DispatcherObject
,可访问UI线程的Dispatcher
。 - Gennady Vanin Геннадий Ванин