C # Practice 2 async keyword

reference:

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/async

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/

 

" This is the goal of this syntax: Support Code reads like a series of statements, but will be performed in a more complex sequence based on external resource allocation and task completion time. "

Implementation: Code written in a serial manner, but they can not follow the implementation of the serial. asynchronous.

 

 

Code:

private static async Task<bool> RunStreamingDemo(string host, int port)
{
...
}

 

 

Code:

static async Task Main(string[] args)
{
    Coffee cup = PourCoffee();
    Console.WriteLine("coffee is ready");
    var eggsTask = FryEggsAsync(2);
    var baconTask = FryBaconAsync(3);
    var toastTask = MakeToastWithButterAndJamAsync(2);

    var allTasks = new List<Task>{eggsTask, baconTask, toastTask};
    while (allTasks.Any())
    {
        Task finished = await Task.WhenAny(allTasks);
        if (finished == eggsTask)
        {
            Console.WriteLine("eggs are ready");
        }
        else if (finished == baconTask)
        {
            Console.WriteLine("bacon is ready");
        }
        else if (finished == toastTask)
        {
            Console.WriteLine("toast is ready");
        }
        allTasks.Remove(finished);
    }
    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");
    Console.WriteLine("Breakfast is ready!");

    async Task<Toast> MakeToastWithButterAndJamAsync(int number)
    {
        var toast = await ToastBreadAsync(number);
        ApplyButter(toast);
        ApplyJam(toast);
        return toast;
    }
}

  

" This final code is asynchronous. It is a more accurate reflection of a person for breakfast processes. The first code example above code in this article are compared. When reading the code, the core operation is still very clear. You can follow read this article in the same way as reading instructions for making breakfast at the start of this code asyncand awaitlanguage features to support everyone to make a change in writing to follow these instructions: start the task as much as possible, do not cause obstruction while waiting for the completion of the task . "

 

 

Guess you like

Origin www.cnblogs.com/alexYuin/p/12397329.html