当BackgroundWorker发生异常时,在不同的线程上触发代码?

发布于 2024-09-06 04:19:44 字数 177 浏览 1 评论 0原文

我有一个后台工作人员运行并寻找东西,当它找到东西时,我想更新我的主 WinForm。我遇到的问题是,当我尝试从后台工作人员更新 WinForm 时,我收到错误,告诉我无法修改在后台工作人员之外所做的内容(换句话说,我的表单中的所有内容) )。

有人可以提供一个简单的代码示例来说明如何让我的代码按照我想要的方式工作吗?谢谢!

I have a background worker that runs and looks for stuff, and when it finds stuff, I want to update my main WinForm. The issue that I'm having is that when I try to update my WinForm from my background worker, I get errors that tell me I can't modify things that were made outside of my background worker (in other words, everything in my form).

Can someone provide a simple code example of how I can get my code to work the way I want it to? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北渚 2024-09-13 04:19:44

我相信您正在寻找 OnProgressChanged 事件。有关示例的更多信息:http://msdn。 microsoft.com/en-us/library/system.componentmodel.backgroundworker.onprogresschanged.aspx

I believe you're looking for the OnProgressChanged Event. More info with example here: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.onprogresschanged.aspx

剩一世无双 2024-09-13 04:19:44

如果我理解正确,您想要对表单本身进行更改,但是您不能从创建表单的线程以外的线程更改表单上的控件。为了解决这个问题,我使用 Form.Invoke() 方法,如下所示:

public void DoSomething(string myArg) 
{
    if(InvokeRequired) 
    {
        Invoke(new Action<string>(DoSomething), myArg);
    }
    else
    {
        // Do something here
    }
}

InvokeRequired 属性检查调用线程以确定它是否是对表单进行更改的正确线程,如果不是,则 Invoke 方法会将调用移动到表单的窗口上线。

If I understand correctly, you want to make a change on the form itself, however you cannot change a control on a form from a thread other than the thread the form was created on. To get around this I use the Form.Invoke() method like so:

public void DoSomething(string myArg) 
{
    if(InvokeRequired) 
    {
        Invoke(new Action<string>(DoSomething), myArg);
    }
    else
    {
        // Do something here
    }
}

The InvokeRequired property checks the calling thread to determine if it is the proper thread to make changes to the form, if no the Invoke method moves the call onto the form's window thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文