WPF:如何使用BackgroundWorker处理错误 [英] WPF: How to handle errors with a BackgroundWorker

查看:140
本文介绍了WPF:如何使用BackgroundWorker处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Windows客户端编程,我有点新手。我有一个后台工作者有一个DoWork事件和一个RunCompleted事件连线。如果在DoWork中抛出异常,我想更改我的UI,但是我不能因为它在一个不同的线程。我可以将错误传达给RunCompleted,但这并不能帮助我。

解决方案

调用Dispatcher.BeginInvoke。基本上,你需要这样的代码:

  void UpdateState(WhatEverType someObject)
{
if(! Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal,new Action(()=> UpdateState(someObject));
}
else
{
//使UI改变在这里
}
}


I am a bit of a newbie when it comes to windows client programming. I have a background worker that has a DoWork event and a RunCompleted event wired up. 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. I can communicate the error to RunCompleted, but that doesn't help me either.

解决方案

call 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.
    }
}

这篇关于WPF:如何使用BackgroundWorker处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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