當我使用如下所示的AddListBoxItem函數內的調用軟件變得反應遲鈍和凍結,但如果我使用BeginInvoke它的工作原理。爲什麼會發生?當使用並行BeginInvoke工作,而調用不是 - c#4.0
Visual Studio 2010中,C#4.0
private void button2_Click(object sender, EventArgs e)
{
var watch = Stopwatch.StartNew();
Parallel.For(2, 20, (i) =>
{
var result = SumRootN(i);
AddListBoxItem("root " + i + " : " + result);
});
AddListBoxItem(watch.ElapsedMilliseconds.ToString());
}
private delegate void AddListBoxItemDelegate(object item);
private void AddListBoxItem(object item)
{
if (this.listBox1.InvokeRequired)
{
this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
}
else
{
this.listBox1.Items.Add(item);
}
}
我怎麼能在不同的線程中調用它?我的意思是調用parallel.for? – MonsterMMORPG
@MonsterMMORPG:從其他任何線程* BackgroundWorker或使用ThreadPool.QueueUserWorkItem - 甚至Task.Factory.StartNew,從另一個線程執行*整件事*。 –
我認爲任務是更好的感謝回答。現在我明白了爲什麼變得沒有反應:) – MonsterMMORPG