async
method in C# asynchronous programming: Task
or void
? When programming asynchronously using C#, the async
method can return Task
or void
. This choice is crucial because it determines the behavior of the method and how it interacts with the calling code.
Task
Usually, when you want to expose the progress or result of an asynchronous operation to the caller, you should return Task
. This allows the caller to wait for the task and continue execution after it is completed. Returning Task
can also use exception handling and asynchronous modes, such as async-foreach
, where the progress of multiple tasks can be monitored.
void
The only suitable case for returning void
from the async
method is when you explicitly need the return type, such as in an event handler or UI callback. In these cases, the caller should not be able to wait for the method, and the async
and await
keywords are not required.
avoid top level
Methods marked have special semantics and should be used with caution. They represent top-level asynchronous operations and have different exception handling rules than methods that return tasks. Exceptions in the top level void
method are treated as unhandled exceptions and can lead to unexpected behavior.
For example, consider the following code:
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
async void is unnecessary and may be problematic because:
method and the await
keyword to ensure correct exception handling and maintain the ability to track and manage asynchronous operations.
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