C # personal note

Foreword

Record what C # is something a lot of foundation or not, or recommend Microsoft's official website documents, online blog writing are too water, or a little better document the official website

Microsoft's official documentation

Asynchronous tasks

Shortcoming synchronization method

In fact, I most want to say is this, I give an example, there are two methods, methods 1 and 2, I would like to perform the method then perform method 2, if I order execution, then must wait for the process execution is completed method 2 only after the code 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 know, must wait for the completion of the implementation process will be implemented method, for example, I would like to boil water for cooking, such as water must be boiled vegetables vegetable ...... which I can obviously be while doing things that we can use asynchronous solutions

Asynchronous Methods

The two cases, I / O and CPU operations, I am here temporarily useless to I / O so do not write, talk about the operation of the CPU

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);
    }
}

Feature is async, Task or Task<T>, await, Task.Run these

返回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);
}

Guess you like

Origin www.cnblogs.com/yunquan/p/11260330.html