C# Personal Notes

Keywords: PHP

Catalog

Preface

Record some things in C #, base a lot or not, or recommend Microsoft's official documents, online blogs are too watery, or official documents better.

Microsoft Official Documents

Asynchronous tasks

Disadvantages of Synchronization Method

Actually, what I want to talk about most is this. For example, there are two methods, method 1 and method 2. Now I want to execute method 1 first and then method 2. If I execute method 2 sequentially, then I have to wait for method 1 to execute before executing method 2 as follows.

static void Main(string[] args)
{
    method1();
    method2();
}

public static void method1()
{
    for (int i = 0; i < 80; i++)
    {
System.Console.WriteLine("method1: "+i);
    }
}
public static void method2() {
    for (int i = 0; i < 20; i++)
    {
System.Console.WriteLine("method2: "+i);
    }
}

Execution will tell you that you have to wait for method 1 to finish before you can implement method 2. For example, if I want to cook with water, I have to wait for water to boil before I can wash and cut vegetables... This is clearly something that can be done at the same time, and we can use asynchronous method to solve it.

Asynchronous method

This is divided into two cases, I/O and CPU operations, I do not use I/O here for the time being, so I do not write, talk about CPU operations.

Return to Task

static void Main(string[] args)
{
    method1();
    method2();
    System.Console.ReadKey();
}

public static async Task method1()
{
    await Task.Run(() =>
    {
 for (int i = 0; i < 80; i++)
 {
     System.Console.WriteLine("method1: " + i);
 }
    });
}
public static void method2() {
    for (int i = 0; i < 20; i++)
    {
 System.Console.WriteLine("method2: "+i);
    }
}

The features are async,Task or Task < T >, await, Task. Run.

Return to Task<T>

 static void Main(string[] args)
{
    callMethod();
    System.Console.ReadKey();
}

public static async void callMethod()
{
    Task<int> task = method1();
    int count = await task;
    method3(count);
}
public static async Task<int> method1()
{
    int count=0;
    await Task.Run(() =>
    {
 for (int i = 0; i < 80; i++)
 {
     System.Console.WriteLine("method1: " + i);
     count++;
 }
    });
    return count;
}
public static void method2()
{
    for (int i = 0; i < 20; i++)
    {
 System.Console.WriteLine("method2: " + i);
    }
}
public static void method3(int count)
{
    System.Console.WriteLine("Count is "+count);
}

Posted by edwardsbc on Tue, 30 Jul 2019 23:18:43 -0700