Aik*_*Aik 4 c# parallel-processing
我在使用System.Threading.Tasks.Parallel.ForEach时遇到问题.身体foreach progressBar想要更新.但Invoke方法有时会冻结.
我将代码附加到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;
}
Run Code Online (Sandbox Code Playgroud)
有时它通过没有问题,但通常它冻结
var result = Invoke (new Action <int> (Set), i).试着解决我的问题.
谢谢.
您的问题是Invoke(并向TaskUI 排队TaskScheduler)都需要UI线程处理其消息循环.但事实并非如此.它仍在等待Parallel.ForEach循环完成.这就是你看到僵局的原因.
如果您希望在Parallel.ForEach不阻塞UI线程的情况下运行,请将其包装成一个Task,如下所示:
private TaskScheduler ui;
private void button1_Click(object sender, EventArgs e)
{
ui = TaskScheduler.FromCurrentSynchronizationContext();
DateTime start = DateTime.Now;
Task.Factory.StartNew(pforeach)
.ContinueWith(task =>
{
task.Wait(); // Ensure errors are propogated to the UI thread.
Text = (DateTime.Now - start).ToString();
}, ui);
}
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);
Task.Factory.StartNew(
() => Set(value),
CancellationToken.None,
TaskCreationOptions.None,
ui).Wait();
return count;
},
(x) =>
{
});
}
private void Set(int i)
{
progressBar1.Value = i;
}
Run Code Online (Sandbox Code Playgroud)