Home > Backend Development > C#.Net Tutorial > Detailed explanation of the use of async and await in C#

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

黄舟
Release: 2017-09-09 15:35:32
Original
2095 people have browsed it

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<double> 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); 
  } 
}
Copy after login

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 Task 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<double> awaiter = GetValueAsync(1234.5, 1.01).GetAwaiter(); 
  awaiter.OnCompleted(() => 
    { 
      double result = awaiter.GetResult(); 
      System.Diagnostics.Debug.WriteLine("Value is : " + result); 
    }); 
}
Copy after login

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 
{ 
  /// <summary> 
  /// 将一个方法function异步运行,在执行完毕时执行回调callback 
  /// </summary> 
  /// <param name="function">异步方法,该方法没有参数,返回类型必须是void</param> 
  /// <param name="callback">异步方法执行完毕时执行的回调方法,该方法没有参数,返回类型必须是void</param> 
  public static async void RunAsync(Action function, Action callback) 
  { 
    Func<System.Threading.Tasks.Task> taskFunc = () => 
    { 
      return System.Threading.Tasks.Task.Run(() => 
      { 
        function(); 
      }); 
    }; 
    await taskFunc(); 
    if (callback != null) 
      callback(); 
  } 
 
  /// <summary> 
  /// 将一个方法function异步运行,在执行完毕时执行回调callback 
  /// </summary> 
  /// <typeparam name="TResult">异步方法的返回类型</typeparam> 
  /// <param name="function">异步方法,该方法没有参数,返回类型必须是TResult</param> 
  /// <param name="callback">异步方法执行完毕时执行的回调方法,该方法参数为TResult,返回类型必须是void</param> 
  public static async void RunAsync<TResult>(Func<TResult> function, Action<TResult> callback) 
  { 
    Func<System.Threading.Tasks.Task<TResult>> taskFunc = ()=> 
      { 
        return System.Threading.Tasks.Task.Run(()=> 
          { 
            return function(); 
          }); 
      }; 
    TResult rlt = await taskFunc(); 
    if(callback != null) 
      callback(rlt); 
  } 
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template