Exception handling of asynchronous void
methods
When using Microsoft's Async CTP for asynchronous programming, it is crucial to understand the exception handling behavior of asynchronous void
methods. Consider the following scenario:
<code class="language-csharp">public async void Foo() { var x = await DoSomethingAsync(); } public void DoFoo() { try { Foo(); } catch (ProtocolException ex) { // 异常将永远不会被捕获。 } }</code>
The question is: Can the exception thrown in the asynchronous method DoFoo
be caught in the calling method Foo
?
Answer: Yes (but there are prerequisites)
Exceptions do bubble up to the calling code, but only if you require a call to await
or Wait()
Foo
. Modify the code as follows:
<code class="language-csharp">public async Task Foo() { var x = await DoSomethingAsync(); } public async void DoFoo() { try { await Foo(); } catch (ProtocolException ex) { // 异常将被捕获,因为它是一个异步方法。 } } public void DoFoo() { try { Foo().Wait(); } catch (ProtocolException ex) { // 异常将被捕获,因为调用被等待。 } }</code>
This allows exception handling in the calling code.
However, it is important to note that Stephen Cleary, an authority on asynchronous programming, warns:
Additionally, using"Async
void
methods have different error handling semantics. When an exception is thrown from an asyncTask
or asyncTask<T>
method, the exception is caught and placed on theTask
object. Right For asyncvoid
methods, there is noTask
object, so any exception thrown from an asyncvoid
method will be raised directly on thevoid
that was active when the asyncSynchronizationContext
method was initiated.
to wait for a task to complete may block the application if .NET decides to execute the method synchronously. Wait()
The above is the detailed content of Can Exceptions Thrown in Async Void Methods Be Caught by Calling Methods?. For more information, please follow other related articles on the PHP Chinese website!