Search code examples
c#backgroundworker

BackgroundWorker crashes if reporting progress


I have a BackgroundWorker that calls a method in a class. The method is given a reference to the BackgroundWorker so that it can report back its progress. This pseudocode shows the outline:

void BackgroundWorker_DoWork( object sender )
{
    BackgroundWorker w = sender as BackgroundWorker;
    var c = new ProcessingClass()
    c.someMethod( w )
}

class ProcessingClass()
{
    someMethod( BackgroundWorker w )
    {
        w.ReportProgress(50)
        //calculations...
    }
}

The problem is that when doing the "calculations" after reporting the progress, the program will crash. the debugger jumps to Application.Run( new frmMain() ); in the startup "Program" class, reason given "Exception has been thrown by the target of an invocation."

If I don't report the progress, everything works fine. Does anyone know why? My guess is that this has something to do with threads, but I don't see how.


Solution

  • Just some suggestions:

    1.) Inspect the InnerException property of the TargetInvocationException exception.

    2.) Configure Visual Studio to stop as soon as the exception is thrown:

    enter image description here

    This should help getting closer to the error.