什么是从一个工作线程更新表单控件的最好方法? [英] What is the best way to update form controls from a worker thread?

查看:116
本文介绍了什么是从一个工作线程更新表单控件的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've done some research and I can't really find a preferred way to do updating of form controls from a worker thread in C#. I know about the BackgroundWorker component, but what is the best way to do it without using the BackgroundWorker component?

推荐答案

有一个普遍凭经验,说不要更新从非UI线程本身以外的任何线程的用户界面。使用BackgroundWorker的特点是一个好主意,但你不希望有什么东西发生在不同的线程,你应该做一个调用或BeginInvoke来迫使委托给UI线程上执行的方法。

There's a general rule of thumb that says don't update the UI from any thread other than the UI thread itself. Using the features of the BackgroundWorker is a good idea, but you don't want to and something is happening on a different thread, you should do an "Invoke" or BeginInvoke to force the delegate to execute the method on the UI thread.

编辑:乔恩乙方在意见中提出这点好:

Jon B made this good point in the comments:

请在介意的invoke()是
同步和的BeginInvoke()是
异步的。如果你使用的invoke(),您
必须注意不要造成一个
僵局。我建议
的BeginInvoke(),除非你真的需要
调用是同步的。

Keep in mind that Invoke() is synchronous and BeginInvoke() is asynchronous. If you use Invoke(), you have to be careful not to cause a deadlock. I would recommend BeginInvoke() unless you really need the call to be synchronous.

一些简单的例子代码:

// 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."});



上面的代码是一个关于它的此处和更长更只有一个相关的这里

The code above is from a FAQ about it here and a longer more involved one here.

这篇关于什么是从一个工作线程更新表单控件的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆