尝试逐步调试中的BackgroundWorker代码,但程序意外结束 [英] Trying to step through BackgroundWorker code in debug but program ends unexpectedly

查看:89
本文介绍了尝试逐步调试中的BackgroundWorker代码,但程序意外结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

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
}

我没有看到任何异常被抛出.我在DoWork的try块中设置了一个断点.有时它会到达断点,但在经过一定数量的行后,程序将结束.它并不总是以同一行代码结尾.有时它根本没有达到断点.

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.

忘了提一下,如果我注释掉Dispose(),它仍然不会逐步执行.

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

推荐答案

尝试在mainWorker.Dispose();之前添加Console.Readline();.您的应用程序有可能在BackgroundWorker完成其工作之前停止.

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

BackgroundWorker以后台线程运行,因此如果终止,它将终止主线程停止.

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();
}

但是如果您添加按Console.Readline();停止主线程,则将拥有所有编号,并且可以在调试中单步执行DoWork代码.

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.

这篇关于尝试逐步调试中的BackgroundWorker代码,但程序意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆