Async and await are introduced in C # 5.0

Source: Internet
Author: User

Async and await are introduced in C # 5.0. These two keywords can make it easier for you to write asynchronous code.

Look at an example:

[CSharp]View Plaincopy
  1. Public class MyClass
  2. {
  3. Public MyClass ()
  4. {
  5. Displayvalue (); //There is no blocking
  6. System.Diagnostics.Debug.WriteLine ("MyClass () End.");
  7. }
  8. Public task<double> getvalueasync (double num1, double num2)
  9. {
  10. return Task.run (() =
  11. {
  12. For (int i = 0; i < 1000000; i++)
  13. {
  14. NUM1 = num1/num2;
  15. }
  16. return NUM1;
  17. });
  18. }
  19. Public async void Displayvalue ()
  20. {
  21. double result = await Getvalueasync (1234.5, 1.01); //This will open a new thread to process the Getvalueasync task, and then return the method immediately
  22. All code after this is encapsulated as a delegate, which is called when the Getvalueasync task completes
  23. System.Diagnostics.Debug.WriteLine ("Value is:" + result);
  24. }
  25. }

The ASYNC keyword tag is called asynchronously in the MyClass constructor, Displayvalue (), and the Displayvalue () method executes an await keyword-tagged asynchronous task Getvalueasync (), This asynchronous task must be either a task or a task<tresult> as the return value, and we also see that the actual type returned when the asynchronous task execution completes is void or the Tresult,displayvalue () method await All code after Getvalueasync () will be executed when the asynchronous task is completed.

The code that is actually executed by the Displayvalue () method is as follows:

[CSharp]View Plaincopy
  1. Public void Displayvalue ()
  2. {
  3. system.runtime.compilerservices.taskawaiter<double> awaiter = Getvalueasync (1234.5, 1.01).  Getawaiter ();
  4. Awaiter. OnCompleted (() =
  5. {
  6. double result = Awaiter.  GetResult ();
  7. System.Diagnostics.Debug.WriteLine ("Value is:" + result);
  8. });
  9. }


As you can see, the async and await keywords simply make the above code easier to understand.

The output of the program is as follows:

MyClass () End.

Value is:2.47032822920623e-322

Here is a static Class I wrote that makes it easy to execute an asynchronous invocation of a normal function:

[CSharp]View Plaincopy
  1. Public static class Taskasynchelper
  2. {
  3. // <summary>
  4. /// to run a method function asynchronously and execute the callback when execution is complete callback
  5. // </summary>
  6. /// <param name= "function" > Async method, the method has no arguments, the return type must be void</param>
  7. // <param name= "Callback" > The callback method executed when the Async method executes, with no arguments, the return type must be void</param>
  8. public static async void RunAsync (action function, action callback)
  9. {
  10. Func<system.threading.tasks.task> Taskfunc = () =
  11. {
  12. return System.Threading.Tasks.Task.Run (() =
  13. {
  14. function ();
  15. });
  16. };
  17. await Taskfunc ();
  18. if (callback! = null)
  19. Callback ();
  20. }
  21. // <summary>
  22. /// to run a method function asynchronously and execute the callback when execution is complete callback
  23. // </summary>
  24. // <typeparam name= "TResult" > Return type of async method </typeparam>
  25. /// <param name= "function" > Async method, the method has no arguments, the return type must be tresult</param>
  26. // <param name= "Callback" > The callback method executed when the Async method executes, the method parameter is TResult, the return type must be void</param>
  27. public static async void Runasync<tresult> (func<tresult> function, action<tresult> Callback)
  28. {
  29. Func<system.threading.tasks.task<tresult>> Taskfunc = () =
  30. {
  31. return System.Threading.Tasks.Task.Run (() =
  32. {
  33. return function ();
  34. });
  35. };
  36. TResult RLT = await taskfunc ();
  37. if (callback! = null)
  38. Callback (RLT);
  39. }
  40. }


It is easy to use the method name as a parameter, and the most common thing is to pass the time-consuming serialization function in order to avoid blocking the UI process, causing the lag and affecting the user experience.

Async and await are introduced in C # 5.0

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.