Home  >  Article  >  Backend Development  >  Detailed explanation of the use of async and await in C#

Detailed explanation of the use of async and await in C#

黄舟
黄舟Original
2017-09-09 15:35:321927browse

This article mainly introduces the specific usage of async and await in C#. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

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

Look at an example:


public class MyClass 
{ 
  public MyClass() 
  { 
    DisplayValue(); //这里不会阻塞 
    System.Diagnostics.Debug.WriteLine("MyClass() End."); 
  } 
  public Task GetValueAsync(double num1, double num2) 
  { 
    return Task.Run(() => 
    { 
      for (int i = 0; i < 1000000; i++) 
      { 
        num1 = num1 / num2; 
      } 
      return num1; 
    }); 
  } 
  public async void DisplayValue() 
  { 
    double result = await GetValueAsync(1234.5, 1.01);//此处会开新线程处理GetValueAsync任务,然后方法马上返回 
    //这之后的所有代码都会被封装成委托,在GetValueAsync任务完成时调用 
    System.Diagnostics.Debug.WriteLine("Value is : " + result); 
  } 
}

The above calls the asynchronous method DisplayValue() marked with the async keyword in the constructor of MyClass, DisplayValue () method executes an asynchronous task GetValueAsync() marked with the await keyword. This asynchronous task must use Task or Taskb54c2c292509147c0b54128f4eb90887 as the return value, and we have also seen that the type actually returned when the asynchronous task execution is completed Whether it is void or TResult, all code after await GetValueAsync() in the DisplayValue() method will be executed when the asynchronous task is completed.

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


public void DisplayValue() 
{ 
  System.Runtime.CompilerServices.TaskAwaiter awaiter = GetValueAsync(1234.5, 1.01).GetAwaiter(); 
  awaiter.OnCompleted(() => 
    { 
      double result = awaiter.GetResult(); 
      System.Diagnostics.Debug.WriteLine("Value is : " + result); 
    }); 
}

As you can see, the async and await keywords just change the above code into Just simpler and easier to understand.

The output of the program is as follows:

MyClass() End.
Value is : 2.47032822920623E-322

The following is one I wrote Static class can facilitate asynchronous calling of a common Function:


public static class TaskAsyncHelper 
{ 
  ///  
  /// 将一个方法function异步运行,在执行完毕时执行回调callback 
  ///  
  /// 异步方法,该方法没有参数,返回类型必须是void 
  /// 异步方法执行完毕时执行的回调方法,该方法没有参数,返回类型必须是void 
  public static async void RunAsync(Action function, Action callback) 
  { 
    Func taskFunc = () => 
    { 
      return System.Threading.Tasks.Task.Run(() => 
      { 
        function(); 
      }); 
    }; 
    await taskFunc(); 
    if (callback != null) 
      callback(); 
  } 
 
  ///  
  /// 将一个方法function异步运行,在执行完毕时执行回调callback 
  ///  
  /// 异步方法的返回类型 
  /// 异步方法,该方法没有参数,返回类型必须是TResult 
  /// 异步方法执行完毕时执行的回调方法,该方法参数为TResult,返回类型必须是void 
  public static async void RunAsync(Func function, Action callback) 
  { 
    Func> taskFunc = ()=> 
      { 
        return System.Threading.Tasks.Task.Run(()=> 
          { 
            return function(); 
          }); 
      }; 
    TResult rlt = await taskFunc(); 
    if(callback != null) 
      callback(rlt); 
  } 
}

It is very simple to use, just pass the method name as a parameter. The most commonly used method is to The serialization function is passed in to avoid blocking the UI process, causing lag and affecting the user experience.

The above is the detailed content of Detailed explanation of the use of async and await in C#. 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