In asynchronous programming, the return value of the method is
or will have a significant effect. This article will explore the applicable scenes of each choice. async
Task
Return to task void
Usually, the method should return . This allows calling code this task and tracking its progress when necessary. The main exception of this rule is when you clearly need
to return the type, such as handling events.
async
Return to VOID Task
await
void
Use the return type
abnormality in the asynchronous method will not be observed under default. They will become an unprepared exception and may trigger the processing program.
Consider the following example:
void
async
In this example, Task
and void
Keywords are unnecessary because there is no need to explicitly handle abnormalities. However, if abnormalities occur, it will not be observed and may not be processed correctly. TaskScheduler.UnobservedTaskException
public static async void AsyncMethod2(int num) { await Task.Factory.StartNew(() => Thread.Sleep(num)); }
asynchronous methods, please consider the following code: async
await
processing program, which will lead to unfarished behaviors. <> Best practice
Task
As the best practice, unless you clearly need void
to return the type, you will always return
static async void f() { await h(); } static async Task g() { await h(); } static async Task h() { throw new NotImplementedException(); }
the task and track its progress. f
g
For more details, please refer to Microsoft's document on TaskScheduler.UnobservedTaskException
/
https://www.php.cn/link/d3ddedd999aa150F47C2D0A55CB17898
The above is the detailed content of Async/Await: Should I Return a Task or Void?. For more information, please follow other related articles on the PHP Chinese website!