我试图在多线程环境中更新进度条.我知道很多问题已经解决了这个问题,但提议的解决方案都没有对我有用.这是我的代码的主干:
public static void DO_Computation(//parameters) {
//Intialisation of parameters
Parallel.For(struct initialisation with local data) {
//business logic
//Call to update_progressbar (located in an another class, as the DO_Computation function is in Computation.cs class (not deriving from Form).
WinForm.Invoke((Action)delegate {Update_Progress_Bar(i);}); //WinForm is a class that exposes the progressbar.
}
}
Run Code Online (Sandbox Code Playgroud)
这是行不通的(当达到100%时,进度条会冻结,这是正常的(我们可以参考这篇文章中的微软文章(实际上,这不是一种线程安全的操作方法).)Microsoft网站用于包装所述Parallel.For环成Task例程如下:
public static void DO_Computation(//parameters) {
//Intialisation of parameters
Task.Factory.StartNew(() =>
{
Parallel.For(struct initialosation with local data) {
//business logic
//Call to update_progressbar …Run Code Online (Sandbox Code Playgroud)