我在使用System.Threading.Tasks.Parallel.ForEach時遇到了問題。進度條正文要更新。 但調用方法有時會凍結。調用並行化foreach的問題
我將代碼附加到prograssbar和Buton的表單中。
private void button1_Click(object sender, EventArgs e)
{
DateTime start = DateTime.Now;
pforeach();
Text = (DateTime.Now - start).ToString();
}
private void pforeach()
{
int[] intArray = new int[60];
int totalcount = intArray.Length;
object lck = new object();
System.Threading.Tasks.Parallel.ForEach<int, int>(intArray,
() => 0,
(x, loop, count) =>
{
int value = 0;
System.Threading.Thread.Sleep(100);
count++;
value = (int)(100f/(float)totalcount * (float)count);
Set(value);
return count;
},
(x) =>
{
});
}
private void Set(int i)
{
if (this.InvokeRequired)
{
var result = Invoke(new Action<int>(Set), i);
}
else
progressBar1.Value = i;
}
有時它傳遞沒有問題,但通常凍結 var result = Invoke (new Action <int> (Set), i)
。 試着在問題中解決我的問題。
謝謝。
謝謝它做工精細。 – Aik 2010-08-12 14:04:13