从工作线程更新表单控件的最佳方法是什么?

我做了一些研究,我真的找不到从C#中的工作线程更新表单控件的首选方法。 我知道BackgroundWorker组件,但是在不使用BackgroundWorker组件的情况下,最好的方法是什么?

一般的经验法则是不要从UI线程本身以外的任何线程更新UI。 使用BackgroundWorker的function是一个好主意,但是您不希望在不同的线程上发生某些事情,您应该执行“Invoke”或BeginInvoke来强制委托在UI线程上执行该方法。

编辑:Jon B在评论中提出了这个好点:

请记住,Invoke()是同步的,Be​​ginInvoke()是异步的。 如果使用Invoke(),则必须注意不要导致死锁。 除非你真的需要调用同步,否则我会推荐BeginInvoke()。

一些简单的示例代码:

// Updates the textbox text. private void UpdateText(string text) { // Set the textbox text. m_TextBox.Text = text; } public delegate void UpdateTextCallback(string text); // Then from your thread you can call this... m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText), new object[]{"Text generated on non-UI thread."}); 

上面的代码来自此处的常见问题解答以及此处涉及的更长的代码。

为什么不想使用BackgroundWorker来做? 它有一个名为ProgressChanged的精彩回调事件,它允许UI线程了解更新,非常适合于progess条形更新等。

链接到详细信息

这里有一个与此相关的讨论。

基本上,您使用Invoke来完成它。

祝你好运!

在调用Invoke时我也会考虑InvokeRequired(仅限VS2008)。 有时您不会从单独的线程更新UI。 它节省了创建委托等的开销。

 if (InvokeRequired) { //This.Invoke added to circumvent cross threading exceptions. this.Invoke(new UpdateProgressBarHandler(UpdateProgressBar), new object[] { progressPercentage }); } else { UpdateProgressBar(progressPercentage); }