C# 试图在调试中单步执行BackgroundWorker代码,但程序意外结束

C# 试图在调试中单步执行BackgroundWorker代码,但程序意外结束,c#,debugging,backgroundworker,C#,Debugging,Backgroundworker,以下是我正在使用的代码: try { mainWorker = new BackgroundWorker(); mainWorker.DoWork += (sender, e) => { try { //stuff I want to have happen in the background ... //I want to step through the li

以下是我正在使用的代码:

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块内设置了一个断点。有时它会遇到断点,但在单步执行一定数量的行之后,程序将结束。它并不总是在同一行代码上结束。有时它根本就没有到达断点

如果我删除后台工作程序,代码将正常执行

我以前没有实现过后台工作程序,我正试图找出我遗漏了什么,这阻碍了我逐步完成我的代码


编辑:忘了提到如果我注释掉Dispose(),它仍然没有通过。

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

BackgroundWorker正在作为运行,所以如果主线程停止,它将被终止

您可以在简单的示例上测试它。此代码将只显示一个数字

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();
}
static void Main(字符串[]args)
{
BackgroundWorker mainWorker=新的BackgroundWorker();
mainWorker.DoWork+=(发件人,e)=>
{
对于(int i=0;i<5;i++)
{
控制台写入线(i);
睡眠(500);
}
};
mainWorker.RunWorkerAsync();
}

但是如果您添加了,请通过
Console.Readline()停止主线程
您将拥有所有的数字,可以在调试中单步执行代码。

还可以检查可能退出主线程的异常。

我发现为了抛出异常,以便我可以通过backgroundworker线程中运行的代码进行调试,我需要启用“仅启用我的代码”在工具=>选项=>调试=>常规=>仅启用我的代码中


然后确保在“调试=>异常”中选中“公共语言运行时异常”复选框,以查看抛出的异常和用户未处理的异常。

是控制台应用程序还是winforms?这是控制台应用程序在您提到这一点并在我的OP中查看您的注释之后,我想确认我的项目的输出类型,但它毕竟没有设置为控制台。将输出类型设置为console后,现在可以正确地执行步骤了!因此,如果我尝试在ASP.NET MVC控制器中使用backgroundworker,后台线程将意外终止,对吗??