Home >Backend Development >C++ >Async Task vs. Async Void: When Should You Return a Task?

Async Task vs. Async Void: When Should You Return a Task?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-01 13:56:09647browse

Async Task vs. Async Void: When Should You Return a Task?

In the asynchronous programming,

and return value selection async Task async void It is common to use

and

in asynchronous programming, but choosing async or await as a method of return is often confusing. public async Task AsyncMethod(int num) public async void AsyncMethod(int num) Return

Task In general, returning is the first choice. It allows the caller to track the progress of asynchronous operation and wait for it to complete. This is very useful when the task indicates that it may require a long time to run operations.

Return Task

Return to Usually used for asynchronous operations does not need to report its progress or the recipient does not need to wait for it to complete. A suitable scenario is to deal with events, because event processing procedures are usually not returned. void Non -necessary keywords

void In some cases,

and

may not be necessary. For example, if your method only executes a single asynchronous operation and does not need to track its progress, you can use the following syntax:

However, in this case, it is still recommended to use

and async, because they ensure the correct treatment of abnormalities, especially when the asynchronous operation throws the unprecedented abnormality of the caller. await

Other precautions
<code class="language-csharp">public static void AsyncMethod2(int num)
{
    Task.Factory.StartNew(() => Thread.Sleep(num));
}</code>

async await Methods are considered "top -level" asynchronous operations, and have special rules in abnormal treatment.

If the top -level method is thrown abnormally, the caller does not always observe it. Use and

to ensure that the exception can be properly handled in top and non -top -level asynchronous methods.

The above is the detailed content of Async Task vs. Async Void: When Should You Return a Task?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn