[C #] Three return types of async,

Source: Internet
Author: User

[C #] Three return types of async,
Three return types of async

The blogger has simply written eight asynchronous articles published by himself. This time I want to talk about the async return type separately.

The Asynchronous Method has three return types available for developers: Task <TResult>, Task, and void.

When is the return type required? specific analysis is required. If the program is improperly used, the execution result may not be what you want. Let's talk about how to select different return types for different situations.

 

Directory
  • Return type-Task <TResult>
  • Return type-Task
  • Return type-void
  • Summary

 

I. Return type-Task <TResult>

[Remember] When you add the async keyword, you need to return an object that will be used for subsequent operations. Please useTask <TResult>.

 

Task <TResult> the return type can be used in the async method, which includes the specified typeTResult.

In the following example, the GetDateTimeAsync Asynchronous Method contains a return statement that returns the current time. Therefore, the method declaration must specifyTask<DateTime>.

Async Task <DateTime> GetDateTimeAsync () {// Task. FromResult is a placeholder, type: DateTime return await Task. FromResult (DateTime. Now );}

  

Call the GetDateTimeAsync method:

Async Task CallAsync () {// call method of another Asynchronous Method DateTime now = await GetDateTimeAsync ();}

When GetDateTimeAsync is called from the await expression, the await expression retrieves the DateTime type value stored in the task returned by GetDateTimeAsync.

 

Async Task CallAsync () {// call method in another Asynchronous Method // DateTime now = await GetDateTimeAsync (); // call Task in another way <DateTime> t = GetDateTimeAsync (); dateTime now = await t ;}

Call the GetDateTimeAsync method through the CallAsync method, and return the call to the non-Wait method GetDateTimeAsyncTask<DateTime>. This task is assigned to the DateTimeTaskVariable. Because DateTimeTaskThe variable is Task <DateTime>, that is,TResultIt is of the DateTime type. In this case, TResult indicates the date type. WhenawaitIt is applied to the DateTime type of the Task <DateTime>, and the calculation result of the await expression is the DateTime type of the Task <DateTime>. At the same time, this value is assigned to the now variable.

 

This time, I will demonstrate different variables. You can compare them to see if the results are the same:

Async Task CallAsync () {// call method of another Asynchronous Method DateTime now = await GetDateTimeAsync (); // call Task in another way <DateTime> t = GetDateTimeAsync (); dateTime now2 = await t;
// Compare the output result to the Console. writeLine ($ "now: {now}"); Console. writeLine ($ "now2: {now2}"); Console. writeLine ($ "t. result: {t. result }");}

  

The answer I can give here is: the result is the same.

[Note] the Result attribute of a task is the lock attribute. If you try to read the attribute value before the task is completed, the result is that the currently active thread will be blocked, blocked until the task is completed and the result value is available. In most cases, you should useawaitInstead of directly accessing the attribute.

 

Ii. Return type-Task

[Remember] If you only want to know the execution status and do not need to know the specific returned results, use the Task.

 

Async methods that do not contain return statements, or return statements that do not contain return values, usually have the return type Task. If such a synchronization method is written as async, these methods actually return void. If you useTaskReturn type. You can use the await operator to pause the completion of the call until the called async method ends.

 

See the example:

Async Task DelayAsync () {// Task. Delay is a placeholder used to assume that the method is in the working state. Await Task. Delay (100); Console. WriteLine ("OK! ");}

  

Call and wait for the DelayAsync method by using the await statement instead of the await expression, similar to the call statement of the method that returns void. In this case, the application of the await operator does not generate a value.

See the example of calling DelayAsync.

// Await DelayAsync ();

 

Now, I use to separate the call and wait methods:

// Separate Task delayTask = DelayAsync (); await delayTask;

 

Iii. Return type-void

[Remember] If you don't want to worry about it after the trigger, use void. Such as the event processing program.

 

The void return type is mainly used in event handlers. The void return type can also be used to replace methods that do not return anything, or to execute methods that can be categorized as "no matter what is called. However, you should try to return the typeTask Because the async method of void type cannot be returned by await. Any caller of The async method can only continue to complete (meaning thread blocking may occur), without waiting for the called async method to complete, and the caller should, or any value or exception that must be generated independently of the async method.

The caller of The async method that returns void cannot catch the exception thrown from this method, and this unhandled exception may cause a hard-to-find fault in your program. If exceptions occur in the async method of the returned Task Type or Task <TResult> type, such exceptions are stored in the returned Task and will be triggered again when await is the Task. That is to say, please use Task <TResult> and Task as much as possible so that the call can read the exception information and select how to handle it.

Now, await can be used for exceptions. Please go back to C #'s past and present-witness new syntax features of c #6.0.

 

Void return value example:

Private async void button#click (object sender, EventArgs e) {// start the process and wait for await Task. Delay (100 );}

 

Summary
  • After you add the async keyword, you need to return an object that will be used for subsequent operations. Use Task <TResult>;

  • If you only want to know the execution status, but do not need to know the specific returned results, use the Task;

  • If you don't want to worry about it after the trigger, use void.

  • Use Task <TResult> and Task as the return type of The async method whenever possible.

 

Asynchronous programming Series

 

 

[Blogger] Anti-Bot

[Source] http://www.cnblogs.com/liqingwen/p/6218994.html

[Reference] Microsoft official documentation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.