我做了一些研究,我真的找不到从C#中的工作线程更新表单控件的首选方法。我知道BackgroundWorker组件,但是在不使用BackgroundWorker组件的情况下,最好的方法是什么?
发布于 2019-04-08 08:18:12
有一个通用的经验法则说,不要从UI线程本身以外的任何线程更新UI。使用BackgroundWorker的功能是一个好主意,但是您不希望在不同的线程上发生某些事情,您应该执行“Invoke”或BeginInvoke以强制委托在UI线程上执行该方法。
编辑:Jon B在评论中提出了这个好点:
请记住,Invoke()是同步的,BeginInvoke()是异步的。如果使用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."});
https://stackoverflow.com/questions/-100001079
复制相似问题