Task asynchronous programming in c #

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/index translation

1. introduction

  Task Asynchronous Programming Model (TAP) provides an abstraction of the asynchronous code, as a code sequence of statements, the next stage can be completed before the start of reading the code at each stage of the process, the compiler converts a number, because some statement may start work in progress and return to the task.

  Task goal is asynchronous programming, startup code similar to the sequence of statements, but when task execution is completed, perform tasks to a more complex sequence based on external resource allocation, similar to how people issued a directive for the process include asynchronous tasks.

2. Asynchronous Programming

  Herein, by way of example a breakfast made to understand how keyword async and await keywords such asynchronous operation includes a series of instructions easier.

  List breakfast manufactured as follows:

  (1) pour a cup of coffee;

  (2) The pan is heated, and then two fried eggs;

  (3) three fried bacon;

  (4) two toast bread;

  (5) Add the butter and jam toast;

  (6) pour a glass of orange juice

  Cooking breakfast is a good example of asynchronous work, the same person can go to perform another step before a step is completed. The simple operation of the synchronization code version is as follows:

static void Main(string[] args)
{
    Coffee cup = PourCoffee();
    Console.WriteLine("coffee is ready");
    Egg eggs = FryEggs(2);
    Console.WriteLine("eggs are ready");
    Bacon bacon = FryBacon(3);
    Console.WriteLine("bacon is ready");
    Toast toast = ToastBread(2);
    ApplyButter(toast);
    ApplyJam(toast);
    Console.WriteLine("toast is ready");
    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    Console.WriteLine("Breakfast is ready!");
}

  If the steps given above employ a breakfast ready, the overall efficiency will be very low, and in fact, we can in the process of heating the pan fried egg in fried bacon, bacon after the start, you can put bread toaster. Asynchronous execution of actions in order to achieve, you need to write asynchronous code. Simple asynchronous implementation of the code as follows:

static async void Main(string[] args)
{
    Coffee cup = PourCoffee();
    Console.WriteLine("coffee is ready");
    Egg eggs =await FryEggs(2);
    Console.WriteLine("eggs are ready");
    Bacon bacon =await FryBacon(3);
    Console.WriteLine("bacon is ready");
    Toast toast =await ToastBread(2);
    ApplyButter(toast);
    ApplyJam(toast);
    Console.WriteLine("toast is ready");
    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    Console.WriteLine("Breakfast is ready!");
}

  At this point, fried eggs, fried bacon and toast these three actions is not required in order to perform, when cooking eggs or bacon, the code does not prevent, you can start multiple component tasks simultaneously.

2.1 At the same time start the task

  In many cases, we want to start multiple independent tasks immediately, and then, when each task is completed, you can continue with other work has been prepared. In the above example the breakfast, which is required for faster completion breakfast. In .NET Core, System.Threading.Tasks.Task and related classes can be used to reasoning ongoing task class, this feature makes it easier to write code that actually create closer breakfast the way. Simultaneously start cooking eggs, bacon and toast. When you need to perform each action, we can turn our attention to the task, pay attention to the next action, then wait for the other things that need attention.

  We can start a task and keep the work of the Task object, await the results before treatment, we will complete each task. Creating breakfast above code changes, the first step is to store the operation at the start of the operation, rather than waiting for them.

Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
Task<Egg> eggTask=FryEggs(2);
Egg eggs=await eggTask;
Console.WriteLine("eggs are ready");
Task<Bacon> baconTask=FryBacon(3);
Bacon bacon=await baconTask;
Console.WriteLine("bacon is ready");
Task<Toast> toastTask=ToastBread(2);
Toast toast=await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("toast is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready");

Console.WriteLine("Breakfast is ready!");

  Next, we can await before providing breakfast for frying bacon and fried eggs moved to the end of the statement, as follows:

Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
Task<Egg> eggTask = FryEggs(2);
Task<Bacon> baconTask = FryBacon(3);
Task<Toast> toastTask = ToastBread(2);
Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("toast is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready");

Egg eggs = await eggTask;
Console.WriteLine("eggs are ready");
Task<Bacon> baconTask = FryBacon(3);
Bacon bacon = await baconTask;
Console.WriteLine("bacon is ready");

  The effect of this code better, you can start all asynchronous tasks immediately, wait for each task only when needed results. The code is implemented code similar to the web application can be different micro-service request, and then combined into a single results page. At this time, we will send all requests immediately, and then await all tasks and combined into a web page.

2.2 Task combination  

  The process of making breakfast, the toast is made asynchronous operation (toast) and a combination of synchronous operations (add butter and jam) is. In this case, we need to know, asynchronous operations and combinations of operations subsequent synchronization is asynchronous , i.e., if any part of the operation is asynchronous, the entire operations are asynchronous.

  The following method creates a portfolio of work is given. Before breakfast, if you want to wait any baked bread before adding butter and jam, you can use the following code says:

async Task<Toast> makeToastWithButterAndJamAsync(int number){
      var plainToast=await ToastBreadAsync(number);  
      ApplyButter(plainToast);
      ApplyJsm(plainToast);
      return plainToast;
}

  The above method contains a statement await contains asynchronous operation, which represents the task of baking bread, then add butter and jam, and then returns a Task <TResult>, represent the combined results of these three operations. Lesson current code amended as follows:

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 eggs = await eggsTask;
    Console.WriteLine("eggs are ready");
    var bacon = await baconTask;
    Console.WriteLine("bacon is ready");
    var toast = await toastTask;
    Console.WriteLine("toast is ready");
    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    Console.WriteLine("Breakfast is ready!");

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

}

  Modify the code above illustrates the importance of the work of the asynchronous code, separated into operation by the new method returns the task to a combination of tasks, you can choose when to wait for the task, other tasks at the same time start

2.3 effectively waiting for other tasks

  await the well may be a method by using the Task class code at the end of a series of preceding statements, wherein an API is WhenAll , it returns to complete a task is completed in all its Task parameter list, as shown in the following code:

await Task.WhenAll(eggTask,baconTask,toastTask);
Console.WriteLine("eggs are ready");
Console.WriteLine("bacon is ready");
Console.WriteLine("toast is ready");
Console.WriteLine("Breakfast is ready!");

  Another option is to use WhenAny, with its modified tasks return results of a Task <Task>, when we know that the task has been completed, you can wait for the return of any parameters when completed. The following code shows how to use WhenAny wait for the completion of the first task is then processed as a result, after processing the results, delete the completed tasks from the list passed to the task in.

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

  After all the changes, the final version of the main methods are as follows:

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(allTask.Any()){
 Task finished = await Task.WhenAny(allTasks);
if (finished == eggsTask)
        {
            Console.WriteLine("eggs are ready");
            allTasks.Remove(eggsTask);
            var eggs = await eggsTask;
        } else if (finished == baconTask)
        {
            Console.WriteLine("bacon is ready");
            allTasks.Remove(baconTask);
            var bacon = await baconTask;
        } else if (finished == toastTask)
        {
            Console.WriteLine("toast is ready");
            allTasks.Remove(toastTask);
            var toast = await toastTask;
        } else
                allTasks.Remove(finished);
}
Console.WriteLine("Breakfast is ready!");

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

 

Guess you like

Origin www.cnblogs.com/mo-lu/p/11116690.html