Return value of the Async/Await method: Task or Void?
In asynchronous programming, whether the return value of the async
method is Task
or void
has a significant impact. This article will explore the scenarios that each option applies.
Return Task
Usually, the async
method should return Task
. This allows the code await
to be called and track its progress if necessary. The main exception to this rule is when you explicitly need the void
return type, such as when handling events.
Return Void
Tag it as "Top-level asynchronous operation" using the void
return type's method. These operations behave differently when exceptions occur. Unlike the
Task of the return value, exceptions in the
void asynchronous method are not observed by default. They become unhandled exceptions and may trigger the
TaskScheduler.UnobservedTaskException handler.
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
In this example, the async and
await keywords are unnecessary because the exception is not required to be handled explicitly. However, if an exception occurs, it will not be observed and may not be handled correctly.
Exception handling example]
To demonstrate the difference in exception handling betweenTask and
void asynchronous methods, consider the following code:
static async void f()
{
await h();
}
static async Task g()
{
await h();
}
static async Task h()
{
throw new NotImplementedException();
}
If f] is called, the exception is observed and treated as any other unhandled exception. However, if
g] is called, the exception is never observed and will be handled by the
TaskScheduler.UnobservedTaskException handler, which will result in undefined behavior.
Best Practices
As a general best practice, always returnTask from the
async method unless you explicitly need the
void return type. This ensures that the exception is handled correctly and that the caller can select
await the task and track its progress.
async/
await best practices:
https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3