gpt4 book ai didi

c# - 为什么 BackgroundWorker 可以修改 UI 组件?

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:36 25 4
gpt4 key购买 nike

我正在更改 Text来自 BackgroundWorker 的按钮它有效。我认为这应该引发异常。为什么不呢?

为什么我得不到 Cross-thread operation not valid: ... accessed from a thread other than the thread it was created on. ?

编辑:谢谢大家。

也许原因是有一个:Thread.Sleep(1000);在用户界面上。

public Form1()
{
InitializeComponent();

backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerAsync();
Thread.Sleep(1000);
}

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
button1.Text = "a";
}

但是,我注意到以下代码运行良好,尽管影响了 UI(间接)。
public partial class Form1 : Form
{
int i;

public Form1()
{
InitializeComponent();

i = 1;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerAsync();
for (int j = 0; j < 100000000; j++) ;
button1.Text = i.ToString();
}

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
i = 2;
}
}

为什么?

最佳答案

工作完成后后台工作人员调用的回调函数 (BackgroundWorker.RunWorkerCompleted) - 为了您的方便 - 已经使用 UI 线程调度程序。

编辑:

@ispiro:不能保证您的第二个示例中的代码将始终有效 - 您仍然有变量 i 的跨线程更新所以你应该声明它volatile以确保它始终正确更新。

第一个代码不起作用的原因是 .NET 框架可以帮助您检测这种跨线程访问。正如@Greg D 指出的那样,这可以被禁用(这绝对是一个禁忌)。欲了解更多信息,请查看 MSDN page :

The .NET Framework helps you detect when you are accessing your controls in a manner that is not thread safe. When you are running your application in the debugger, and a thread other than the one which created a control tries to call that control, the debugger raises an InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on."

This exception occurs reliably during debugging and, under some circumstances, at run time. You might see this exception when you debug applications that you wrote with the .NET Framework prior to the .NET Framework version 2.0. You are strongly advised to fix this problem when you see it, but you can disable it by setting the CheckForIllegalCrossThreadCalls property to false. This causes your control to run like it would run under Visual Studio .NET 2003 and the .NET Framework 1.1.

关于c# - 为什么 BackgroundWorker 可以修改 UI 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com