【发布时间】:2018-04-22 10:05:41
【问题描述】:
我只是想更新Parallel.ForEach 中的进度条,应用程序似乎冻结了。
尽管我已经按照其他帖子的建议尝试使用Invoke 解决方案,但我仍然遇到问题。
这是我的代码的简化版本:
public partial class Form1 : Form
{
event EventHandler ReportProgress;
class ProgressEvent : EventArgs
{
public int Total { get; set; }
public int Current { get; set; }
}
public Form1()
{
InitializeComponent();
ReportProgress += Form1_ReportProgress;
}
private void Form1_ReportProgress( object sender, EventArgs e )
{
var progress = e as ProgressEvent;
if ( InvokeRequired )
{
this.Invoke( new Action( () => { progressBar.Maximum = progress.Total; progressBar.Value = progress.Current; } ) );
}
}
private void buttonStart_Click( object sender, EventArgs e )
{
// Create a list with seed to be used later
List<int> values = new List<int>() { };
values.AddRange( Enumerable.Range( 1, 15 ) );
var total = values.Count();
var current = 0;
Parallel.ForEach( values, v =>
{
Interlocked.Increment( ref current );
var r = new Random( v );
// Just sleep a little
var sleep = r.Next( 10, 1000 );
Thread.Sleep( sleep );
// Update the progress bar
ReportProgress( null, new ProgressEvent() { Current = current, Total = total } );
}
);
MessageBox.Show( "Done " );
}
}
应用程序似乎挂起并且没有显示消息框,而如果我删除事件生成 (ReportProgress) 一切正常,但显然进度条根本没有更新。
【问题讨论】:
标签: c# winforms parallel.foreach