我在使用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