开发者

How to handle exception raised in BackgroundWorker handler?

I thought that the BackgroundWorker object will trap and pass exceptions raised in the DoWork handler to the RunWorkerCompleted hanlder but it is not happening to my program.

I created the following small program to illustrate the problem. Created wpf app.

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); ExecBackgrpundWorker(); }

    public void ExecBackgrpundWorker()
    {
        var bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);


        bw.RunWorkerAsync();
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        try
        {
        }
        catch (Exce开发者_StackOverflow社区ption ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        throw new NotImplementedException("Do Work Exception");
    }
}

exceptions raised in the bw_DoWork is never passed to the bw_RunWorkerCompleted.

How to properly handle this exception.


The exception is catched by the background thread and assigned to the "Error" property of the RunWorkerCompletedEventArgs parameter of RunWorkerCompleted.


It never makes it to "RunWorkerCompleted" handler. it is failing silently.

My example is checking Active Directory for a list of security groups. I've entered an invalid domain to test the error handling... silent.


Change your code to:

public void ExecBackgrpundWorker()
{
    var bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);


    bw.RunWorkerAsync();
}

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    throw new NotImplementedException("Do Work Exception");
}

If you debugging and get Exception was unhanded by user code, click Continue then you will reach bw_RunWorkerCompleted. When you run your code as release it will always get to bw_RunWorkerCompleted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜