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

痴心易碎 提交于 2019-12-10 16:40:18

问题


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.


回答1:


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.




回答2:


I found that in order for exceptions to be thrown so that I can debug through code running in a backgroundworker thread I need to turn on "Enable Just My Code" in Tools => Options => Debugging => General => Enable Just My Code.

Then make sure that in Debug => Exceptions the "Common Language Runtime Exceptions" checkbox is checked for both Thrown and User-unhandled exceptions.




回答3:


Also check for exceptions which may exits your main thread.



来源:https://stackoverflow.com/questions/19126898/trying-to-step-through-backgroundworker-code-in-debug-but-program-ends-unexpecte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!