【发布时间】:2016-10-25 03:34:06
【问题描述】:
我正在关注这个MSDN guide 来处理任务中的异常。
这是我写的:
var myTask = Task.Run(() =>
{
throw new Exception("test");
});
try
{
myTask.Wait();
}
catch (Exception e)
{
return false;
}
我在catch 块中设置了一个断点,但是在调试运行时,代码没有到达断点,它给了我:
用户代码未处理异常
我不知道发生了什么,因为我非常关注 MSDN 指南中的示例。事实上,我将示例复制到我的项目中,它仍然给出了同样的问题。
有什么方法可以处理任务之外的异常吗?如果任务抛出任何异常,我需要根据事实返回一个布尔值。
编辑
为了让你们中的一些人更清楚,这是一组更完整的代码:
public bool ConnectToService()
{
try
{
// Codes for ServiceHost etc etc, which I'm skipping
// These codes are already commented out for this test, so they do nothing
var myTask = Task.Run(() =>
{
// Supposed to connect to a WCF service, but just throwing a test exception now to simulate what happens when the service is not running
throw new Exception("test");
});
try
{
myTask.Wait();
}
catch (Exception e)
{
return false;
}
return true;
}
catch (Exception)
{
return false;
}
}
来电者:
public void DoSomething()
{
try
{
// Other irrelevant stuff
if (ConnectToService())
{
DoAnotherThing();
}
}
catch (Exception)
{
}
}
我还想指出我有一个解决方案,但令人费解的是为什么 MSDN 中的示例对我不起作用。我会认为我自己的解决方案并不优雅,所以我仍在寻找更优雅的解决方案。
Exception taskException = null;
var myTask = Task.Run(() =>
{
try
{
throw new Exception("test");
}
catch (Exception e)
{
taskException = e;
}
});
try
{
myTask.Wait();
if (taskException != null) throw taskException;
}
catch (Exception e)
{
return false;
}
【问题讨论】:
-
如您所展示的,代码绝对应该到达 catch 块。您使用的是相同的代码还是只是更大代码的演示?
-
@RohitGarg 这是一个大项目的一部分,但出于故障排除的目的,我使用了完全相同的代码(或来自示例),但不知何故它没有到达 catch 块。
标签: c# .net async-await task