我正在使用以下内容
Task.Factory.StartNew(() => DoPrintConfigPage(serial));
Run Code Online (Sandbox Code Playgroud)
然后我调用的函数看起来像这样
private void DoPrintConfigPage(string serial)
{
//do printing work
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在线程内部抛出异常并且没有被处理.
我试过用try catch包装它
try
{
Task.Factory.StartNew(() => DoPrintConfigPage(serial));
}
catch (Exception ex) { }
Run Code Online (Sandbox Code Playgroud)
但它仍然没有捕获错误,从而导致应用程序崩溃.
如何在主线程中捕获异常以便我可以处理它们?
我已经做了下面推荐的更改,但仍然说这个例外是未处理的
var task = Task.Factory.StartNew(() => DoPrintConfigPage(serial))
.ContinueWith(tsk =>
{
MessageBox.Show("something broke");
},TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)
然后在我的DoConfigPage我添加另一个尝试捕获.
在这个问题现在崩溃,并说抛出的异常是未处理的,我错过了什么?
private void DoPrintConfigPage(string serial)
{
try
{
//call the print function
}
catch (Exception ex)
{
throw ex; //it is crashing here and saying it is unhandled
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试了Eric J.所提出的相同结果
var …Run Code Online (Sandbox Code Playgroud)