使用 Microsoft for .NET 的异步 CTP,
是否可以在调用方法中捕获异步方法抛出的异常?
public async void Foo()
{
var x = await DoSomethingAsync();
/* Handle the result, but sometimes an exception might be thrown.
For example, DoSomethingAsync gets data from the network
and the data is invalid... a ProtocolException might be thrown. */
}
public void DoFoo()
{
try
{
Foo();
}
catch (ProtocolException ex)
{
/* The exception will never be caught.
Instead when in debug mode, VS2010 will warn and continue.
The deployed the app will simply crash. */
}
}
所以基本上我希望异步代码中的异常冒泡到我的调用代码中
如果这可能的话。
读起来有点奇怪,但是是的,异常会冒泡到调用代码 - 但只是if you await
or Wait()
打电话给Foo
.
public async Task Foo()
{
var x = await DoSomethingAsync();
}
public async void DoFoo()
{
try
{
await Foo();
}
catch (ProtocolException ex)
{
// The exception will be caught because you've awaited
// the call in an async method.
}
}
//or//
public void DoFoo()
{
try
{
Foo().Wait();
}
catch (ProtocolException ex)
{
/* The exception will be caught because you've
waited for the completion of the call. */
}
}
正如斯蒂芬·克利里 (Stephen Cleary) 在书中写道Async/Await - 异步编程的最佳实践 https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming:
Async void 方法具有不同的错误处理语义。当异步任务或异步任务方法抛出异常时,该异常将被捕获并放置在任务对象上。对于 async void 方法,没有 Task 对象,因此 async void 方法抛出的任何异常都将直接在 async void 方法启动时处于活动状态的 SynchronizationContext 上引发。
请注意,使用Wait()
如果 .NET 决定同步执行您的方法,可能会导致您的应用程序阻塞。
这个解释http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions非常好 - 它讨论了编译器为实现这一魔力而采取的步骤。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)