我只是在嘗試更新進度條,Parallel.ForEach應用程序似乎死機了。盡管我已經(jīng)嘗試過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),一切都將正常運行,但是顯然進度條根本不會更新。
2 回答

白板的微信
TA貢獻1883條經(jīng)驗 獲得超3個贊
您可以更改:
this.Invoke( new Action( () => { progressBar.Maximum = progress.Total; progressBar.Value = progress.Current; } ) );
至:
this.BeginInvoke( new Action( () => { progressBar.Maximum = progress.Total; progressBar.Value = progress.Current; } ) );
這將在異步線程上執(zhí)行操作。
- 2 回答
- 0 關注
- 167 瀏覽
添加回答
舉報
0/150
提交
取消