SoFunction
Updated on 2025-03-07

Tell us about the specific usage of async and await in C#

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

See an example:

public class MyClass 
{ 
  public MyClass() 
  { 
    DisplayValue(); //There won't be blocked here    ("MyClass() End."); 
  } 
  public Task<double> GetValueAsync(double num1, double num2) 
  { 
    return (() => 
    { 
      for (int i = 0; i < 1000000; i++) 
      { 
        num1 = num1 / num2; 
      } 
      return num1; 
    }); 
  } 
  public async void DisplayValue() 
  { 
    double result = await GetValueAsync(1234.5, 1.01);//A new thread will be opened here to process the GetValueAsync task, and then the method will return immediately    //All code after this will be encapsulated as a delegate and called when the GetValueAsync task is completed    ("Value is : " + result); 
  } 
} 

The asynchronous method DisplayValue() of the async keyword tag is called in the MyClass constructor. The DisplayValue() method executes an await keyword tagged as the asynchronous task GetValueAsync(). This asynchronous task must use Task or Task<TResult> as the return value. We also see that the type returned when the asynchronous task is completed is void or TResult. All code after await GetValueAsync() in the DisplayValue() method will be executed only when the asynchronous task is completed.

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

public void DisplayValue() 
{ 
  <double> awaiter = GetValueAsync(1234.5, 1.01).GetAwaiter(); 
  (() => 
    { 
      double result = (); 
      ("Value is : " + result); 
    }); 
}

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

The output of the program is as follows:

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

The following is a static class I wrote that can easily execute asynchronous calls to a normal function:

public static class TaskAsyncHelper 
{ 
  /// &lt;summary&gt; 
  /// Run a method function asynchronously, and execute callback callback when execution is completed  /// &lt;/summary&gt; 
  /// <param name="function">Async method, this method has no parameters, the return type must be void</param>  /// <param name="callback">Callback method executed when the asynchronous method is executed. This method has no parameters, and the return type must be void</param>  public static async void RunAsync(Action function, Action callback) 
  { 
    Func&lt;&gt; taskFunc = () =&gt; 
    { 
      return (() =&gt; 
      { 
        function(); 
      }); 
    }; 
    await taskFunc(); 
    if (callback != null) 
      callback(); 
  } 
 
  /// &lt;summary&gt; 
  /// Run a method function asynchronously, and execute callback callback when execution is completed  /// &lt;/summary&gt; 
  /// <typeparam name="TResult">Return type of asynchronous method</typeparam>  /// <param name="function">Async method, this method has no parameters, the return type must be TResult</param>  /// <param name="callback">Callback method executed when the asynchronous method is executed. The parameter of this method is TResult, and the return type must be void</param>  public static async void RunAsync&lt;TResult&gt;(Func&lt;TResult&gt; function, Action&lt;TResult&gt; callback) 
  { 
    Func&lt;&lt;TResult&gt;&gt; taskFunc = ()=&gt; 
      { 
        return (()=&gt; 
          { 
            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 common thing is to pass the time-consuming serialization function in order to avoid blocking the UI process, causing lag, and affecting the user experience.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.