多线程更新界面
不安全的跨线程调用
直接从未创建控件的线程调用该控件是不安全的.
Visual Studio 调试器通过引发 InvalidOperationException 检测这些不安全线程调用,并显示消息“跨线程操作无效。控件 “” 从创建它的线程以外的线程访问。”在 Visual Studio 调试期间,对于不安全的跨线程调用总是会发生 InvalidOperationException,并且可能在应用运行时发生。 应解决此问题,但也可以通过将 Control.CheckForIllegalCrossThreadCalls 属性设置为 false 来禁用该异常。
安全的跨线程调用
以下代码示例演示了两种从未创建 Windows 窗体控件的线程安全调用该窗体的方法:
System.Windows.Forms.Control.Invoke 方法,它从主线程调用委托以调用控件。
System.ComponentModel.BackgroundWorker 组件,它提供事件驱动模型
System.Windows.Forms.Control.Invoke 方法
this.progressBar1.Invoke(new Action(() => {
this.progressBar1.Value = 10;
}));
BackgroundWorker 组件
实现多线程处理的一种简单方法是使用 System.ComponentModel.BackgroundWorker 组件,该组件使用事件驱动模型。 后台线程运行不与主线程交互的 BackgroundWorker.DoWork 事件。 ==主线程运行 BackgroundWorker.ProgressChanged 和 BackgroundWorker.RunWorkerCompleted 事件处理程序,它们可以调用主线程的控件=。
若要使用 BackgroundWorker 进行线程安全调用,请在后台线程中创建一个方法来完成这项工作,并将其绑定到 DoWork 事件。 在主线程中创建另一个方法来报告后台工作的结果,并将其绑定到 ProgressChanged 或 RunWorkerCompleted 事件。 若要启动后台线程,请调用 BackgroundWorker.RunWorkerAsync.
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerReportsProgress = true; //是否报告执行进度
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
//调用
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string stdPath = e.Argument.ToString(); //获取传入参数
backgroundWorker1.ReportProgress(value); //报告进度,会引发ProgressChanged事件
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage; //更新进度条
}
//执行完成
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.progressBar1.Value = 100;
}
1424

被折叠的 条评论
为什么被折叠?



