Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to step through BackgroundWorker code in debug but program ends unexpectedly

Here is the code I am working with:

try
{
    mainWorker = new BackgroundWorker();
    mainWorker.DoWork += (sender, e) =>
    {
        try
        {
            //stuff I want to have happen in the background
            ...
            //I want to step through the lines in this try block
        }
        catch
        {
            //exception not being caught
        }
    };
    mainWorker.RunWorkerCompleted += (sender, e) =>
    {
        //code to let user know that the background work is done
         ...
    };
    mainWorker.RunWorkerAsync();
    mainWorker.Dispose();
}
catch
{
    //exception not being caught
}

I do not see any exceptions being thrown. I have a breakpoint set inside the try block in DoWork. Sometimes it hits the breakpoint, but after stepping through a certain number of lines the program ends. It doesn't always end on the same line of code. Sometimes it doesn't hit the breakpoint at all.

The code steps through normally if I eliminate the background worker.

I haven't implemented background workers before and I'm trying to figure out what I'm missing that's preventing me from stepping through my code.

edit: forgot to mention that if I comment out Dispose() it still doesn't step through.

like image 718
Krondorian Avatar asked Mar 22 '23 05:03

Krondorian


1 Answers

Try adding Console.Readline(); before mainWorker.Dispose();. It is possible that your application stops before BackgroundWorker does its job.

BackgroundWorker is runing as background thread, so it is terminated if main thread stops.

You can test it on simple example. This code will show only one number.

static void Main(string[] args)
{
    BackgroundWorker mainWorker = new BackgroundWorker();
    mainWorker.DoWork += (sender, e) =>
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(i);
                Thread.Sleep(500);
            }
        };
    mainWorker.RunWorkerAsync();
}

but if you add stop your main thread by Console.Readline(); you will have all the numbers and can step through DoWork code in debug.

like image 190
Dmitrii Dovgopolyi Avatar answered Apr 14 '23 16:04

Dmitrii Dovgopolyi