user1011394
user1011394

Reputation: 1666

BackgroundWorker doesn't handle exception

I've really read all other similar threads on Stackoverflow. Nothing works for me... I throw an exception of type "Exception" but i can't handle the exception.

I've tried it in the DoWork Progress, in the CompletedEvent (with try/catch, witch e.error....)

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

void bgGetResponse_DoWork(object sender, DoWorkEventArgs e)
{
    byte[] test= new byte[] { 1, 1, 0, 1, 1};
    //Here the error occured (just with  throw new Exception("error"))
    //The method only throws an exception (for test purposes)
    testResponse= _configManager.GetResponse(test, 0);
}

GetResponse(...)
{

   throw new Exception("..!");

}

Any ideas?

Thanks for your efforts

Upvotes: 0

Views: 577

Answers (3)

Belmiris
Belmiris

Reputation: 2805

I usually just catch it in the work Method and set the result to it.

private void BGW_DoWork(object sender, DoWorkEventArgs e)
{
    ...
}
catch (Exception ex)
{
    e.Result = ex;
}

Then look in the Completed event,

private void BGW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.Cursor = Cursors.Default;

try
{
    Exception ex = e.Result as Exception;
    if (null != ex)
        throw ex;

...

Upvotes: 2

sam1589914
sam1589914

Reputation: 816

Any unhandled exceptions occuring in the BackgroundWorkers DoWork function will cause the worker to fire RunWorkerCompleted where the event argument will contain the error.

Upvotes: 1

Peter Ritchie
Peter Ritchie

Reputation: 35871

If by "can't handle" the exception you mean can't use catch, that's true. You just use the Error property. You could "throw" that in your Completed event handler; but then you stack frame will be different.

e.g.:

try
{
    if(e.Error != null) throw(e.Error)
    // handle success case
}
catch(MyException exception)
{
    // handle specific error.
}

Upvotes: 1

Related Questions