Kro*_*ian 4 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 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
}
Run Code Online (Sandbox Code Playgroud)
我看不到抛出任何异常。我在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();
}
Run Code Online (Sandbox Code Playgroud)
但是,如果添加停止线程,Console.Readline();则将拥有所有编号,并且可以DoWork在调试中逐步执行代码。
| 归档时间: |
|
| 查看次数: |
2786 次 |
| 最近记录: |