"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Async/Await usage: Task or Void?

Async/Await usage: Task or Void?

Posted on 2025-04-15
Browse:817

Async/Await: Should I Return a Task or Void?

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.

Consider the following example:

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 between

Task 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 return

Task 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.

For more details, please refer to Microsoft's documentation on

async/await best practices: https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming

Latest tutorial More>

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