Asynchronous programming (basic)

1. Asynchronous programming is not multithreading

2. Asynchronous programming only switches the main thread to perform other operations during IO operation / CPU operation without blocking the main thread, so as to improve the concurrency performance of the system

3. Asynchrony can not improve the running speed of the program itself, but can handle more tasks at the same time.

 

Take an example of boiling water (as shown in the figure):

 

The illustration above. From the start of boiling water to boiling water, whether synchronous or asynchronous, the time is the same, but people (main thread) can do more things in the middle.

 

 

Thread slicing also requires overhead. If there is nothing else at present, just boiling water, is it necessary to be asynchronous? What's your opinion?

 

c# asynchronous programming syntax

Asynchronous programming methods are decorated with async

1. The return value is generally Task < T > t is the return value type, and if the return value is empty, Task is returned

2. Mark Async after the method name (indicating that the method is asynchronous). Examples: httpgetstring (synchronous) httpgetstringasync (asynchronous)

3. Get the actual return value of the asynchronous method and add await before calling the method. Example: string str=await httpgetstringasync (asynchronous); If await is not added, the return value type is task < T > and a task thread is directly started to run the modified method without waiting, which may change the execution order of the method

4.await asynchronous non blocking

 

static async Task Main(string[] args)
{

    int result = 0;
    //result= GetNumAsync(99).GetAwaiter().GetResult();//It is not recommended that Ken can deadlock
    result = await GetNumAsync(99);//recommend
    
    Console.WriteLine("Hello, World!");
}
static async Task<int> GetNumAsync(int num)
{
    int result=0;
    for (int i = 0; i < num; i++)
    {
        result += num;
    }
    return result;
}

What are the benefits of an asynchronous approach? For example: (Winfrom program)

 

 

 public Form1()
        {
            InitializeComponent();
        }
    //synchronization
        private void button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(2000);
            this.button1.Text = this.button1.Text + "done.";
        }
        //asynchronous
        private async void button2_Click(object sender, EventArgs e)
        {
            await Task.Delay(2000);
            this.button2.Text = this.button2.Text + "done.";
        }

 

You can compare whether the two buttons can drag the main form after clicking. This is a simple example of main thread blocking. Interface blocking often occurs in Winform and WPF, generally because asynchronous is not used

 

 

 

Asynchronous programming principle:

During wait, the system will return the current thread to the thread pool. After the asynchronous method is completed, take out a thread from the thread pool to continue executing the following code.

Example (get current thread ID):

using System.Text;
{//synchronization
        Console.WriteLine("synchronization Start: "+Thread.CurrentThread.ManagedThreadId);
        WriteText(9999);
        Console.WriteLine("synchronization End: " + Thread.CurrentThread.ManagedThreadId);
    }
    {//asynchronous
        Console.WriteLine("asynchronous Start" + Thread.CurrentThread.ManagedThreadId); 
        await WriteTextAsync(9999);   
        Console.WriteLine("asynchronous End" + Thread.CurrentThread.ManagedThreadId);
    }


//synchronization
static void WriteText(int num)
{
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < num; i++)
    {
        builder.Append("ABCDEFG");
    } 
}


//asynchronous
static Task WriteTextAsync(int num)
{
     StringBuilder builder = new StringBuilder();
    for (int i = 0; i < num; i++)
    {
        builder.Append("ABCDEFG");
    }
    Console.WriteLine("asynchronous Doing" + Thread.CurrentThread.ManagedThreadId);
    return File.WriteAllTextAsync("d:/1.txt",builder.ToString());
}

 

 

 

It can also be seen from the above example that the execution in the asynchronous method is not executed in the new thread, but after execution, another thread will continue to execute the following code.

 

Added by xiaix on Tue, 25 Jan 2022 02:25:56 +0200