简体   繁体   English

WPF:如何使用BackgroundWorker处理错误

[英]WPF: How to handle errors with a BackgroundWorker

I am a bit of a newbie when it comes to windows client programming. 对于Windows客户端编程,我还是个新手。 I have a background worker that has a DoWork event and a RunCompleted event wired up. 我有一个后台工作程序,该工作程序具有DoWork事件和RunCompleted事件。 If an exception gets thrown in DoWork, I want to make changes to my UI, however, I cant because it is in a different thread. 如果在DoWork中引发了异常,我想对UI进行更改,但是我不能,因为它在另一个线程中。 I can communicate the error to RunCompleted, but that doesn't help me either. 我可以将错误传达给RunCompleted,但这也无济于事。

call Dispatcher.BeginInvoke. 调用Dispatcher.BeginInvoke。 Basically, you want code like this: 基本上,您需要这样的代码:

void UpdateState(WhatEverType someObject)
{
    if (! Dispatcher.CheckAccess())
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(()=>UpdateState(someObject));
    }
    else
    {
        //make the UI changes here.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM