Home >Backend Development >C++ >How Can I Catch Exceptions from Async Void Methods in C#?
Handling exceptions in asynchronous void methods
In Microsoft's .NET Async CTP, asynchronous methods behave differently when throwing exceptions. In an asynchronous Task or an asynchronous Task
Catch exception
To catch an exception thrown by an asynchronous void method, you must explicitly wait for the method call or use the Wait() method:
Waiting for method call:
<code class="language-csharp"> public async Task Foo() { var x = await DoSomethingAsync(); } public async void DoFoo() { try { await Foo(); } catch (ProtocolException ex) { // 由于在异步方法中等待了调用,因此将捕获异常。 } }</code>
Use Wait() method:
<code class="language-csharp"> public void DoFoo() { try { Foo().Wait(); } catch (ProtocolException ex) { // 由于等待了调用的完成,因此将捕获异常。 } }</code>
Error handling semantics
As Stephen Cleary pointed out, asynchronous void methods have different error handling semantics:
"When an async void method throws an exception, the exception is raised directly on the SynchronizationContext that was active when the asynchronous void method was started."
Other instructions
The above is the detailed content of How Can I Catch Exceptions from Async Void Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!