SoFunction
Updated on 2025-03-07

C# Task-based asynchronous programming mode (TAP)

Asynchronous programming is an important improvement in C# 5.0, providing two keywords: async and await. Using asynchronous programming, the call of the method is run in the background (usually with the help of a thread or task), but does not block the calling thread. There are three types of asynchronous modes: asynchronous mode, event-based asynchronous mode and task-based asynchronous mode (TAP). TAP is implemented using the keywords async and await. This article will explain the TAP pattern. The async and await keywords are just the functions of the compiler. The compiler will eventually create code with the Task class.

1. Create a task

Creates a synchronous method Greeting, which returns a string after waiting for a while.

 private string Greeting(int delay, string name)
 {
  (delay);
  return ("Hello, {0}.", name);
 }

Defining a method GreetingAsync can make the method asynchronous, and the parameters passed in are not mandatory. Asynchronous mode is specified based on task and returns a task. Note that this method returns Task<string>, which defines a task that returns a string, which is consistent with the return value of the synchronization method.

private Task<string> GreetingAsync(string name, int delay = 3000)
{
 return <string>(() =>
 {
  return Greeting(delay, name);
 });
}

2. Call asynchronous method

The asynchronous method GreetingAsync that returns a task can be called using the await keyword. However, the method of using the await keyword must be declared with the async keyword modifier. Before the GreetingAsync method is completed, the code behind the await keyword in the method modified by the async keyword will not continue to be executed. However, threads that start methods modified by the async keyword can be reused without being blocked.

public async void CallerWithAsync()
{
 string result = await GreetingAsync("Nigel", 2000);
 (result);
}

Note: The async modifier modification can only be used to return methods that return Task or void. It cannot be used as the entry point of the program, that is, the Main method cannot use the async modifier. The await modifier can only be used to return a Task method.

3. Continue the task

The GreetingAsync method returns a Task<string> object. This object contains information about the task creation and saves it until the task is completed. The ContinueWith method of the Task class can continue to call the code after the task is completed.

public void CallsWithContinuationTask()
 {
  Task<string> task = GreetingAsync("Stephanie", 1000);
  (t =>
  {
   ();
  });
 }

In fact, the compiler will put all the code after the await keyword into the ContinueWith method. Whether it is the await keyword method or the ContinueWith method of the task, different threads are used in different life stages of the method. When the method or task of the await keyword is executed, another thread will execute the code behind the await keyword, or add a new task to the current thread to execute the relevant code.

In applications with UI, the controls of the form of the application do not allow cross-thread access. They need to use the InvokeRequired property and Invoke method of the control to pass the method code block that accesses the UI to the Invoke of the control in the form of a delegate, but before execution, you need to judge the InvokeRequired of the control. When using the async and await keywords, when await is completed, you can place the access UI thread without any processing (in fact, you hand over the control to the UI thread again).

4. Use multiple asynchronous methods

4.1. Call multiple asynchronous methods in sequence

Each asynchronous method can be called using the await keyword. If an asynchronous method depends on another asynchronous method, it will play a big role. But when there is no interdependence between asynchronous methods, not using the await keyword will return the result faster.

public async void MultipleAsyncMethods()
 {
  DateTime start = ;
  string result1 = await GreetingAsync("Jack",2500);//Execute it first  string result2 = await GreetingAsync("Tim",1500);//Execute it again  //Output result  ("Finished both methods: MultipleAsyncMethods.\nResult 1: {0}, Result 2: {1}", result1, result2);
  ("Use time: {0}", ( - start).TotalMilliseconds);
 }

4.2. Use the combiner

If tasks do not depend on another task, each asynchronous method does not need to use await, but assigns the return result of each asynchronous method to the Task variable, and uses a combiner to make these tasks run in parallel. The following code will be executed only after all tasks in the combinator are completed.

public async void MultipleAsyncMethodsWithCombinators1()
{
 DateTime start = ;
 Task&lt;string&gt; t1= GreetingAsync("Jack", 2500);
 Task&lt;string&gt; t2= GreetingAsync("Tim", 1500);
 await (t1, t2);
 //Output result ("Finished both methods: MultipleAsyncMethodsWithCombinators1.\nResult 1: {0}, Result 2: {1}", , );
 ("Use time: {0}", ( - start).TotalMilliseconds);
}

If all task types return the same type, an array of that type can be used as the result returned by await

public async void MultipleAsyncMethodsWithCombinators2()
{
 DateTime start = ;
 Task&lt;string&gt; t1 = GreetingAsync("Jack", 2500);
 Task&lt;string&gt; t2 = GreetingAsync("Tim", 1500);
 string[] results= await (t1, t2);
 //Output result ("Finished both methods: MultipleAsyncMethodsWithCombinators2.\nResult 1: {0}, Result 2: {1}", results[0], results[1]);
 ("Use time: {0}", ( - start).TotalMilliseconds);
}

5. Exception handling of asynchronous methods

If an asynchronous method is called but there is no waiting, then using the traditional try/catch block in the thread calling the asynchronous method cannot catch exceptions in the asynchronous method. Because the execution has been completed before an exception occurs in the asynchronous method execution.

How to capture unusual"Error handling in Task-Based Asynchronous Programming Mode (TAP)"

The above is the detailed content of the C# task-based asynchronous programming mode (TAP). For more information about C# asynchronous programming, please pay attention to my other related articles!