How and when to use ‘async’ and ‘await’

前端 未结 21 1571
你的背包
你的背包 2020-11-21 05:07

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perfo

相关标签:
21条回答
  • 2020-11-21 05:36

    The way I understand it is also, there should be a third term added to the mix: Task.

    Async is just a qualifier you put on your method to say it's an asynchronous method.

    Task is the return of the async function. It executes asynchronously.

    You await a Task. When code execution reaches this line, control jumps out back to caller of your surrounding original function.

    If instead, you assign the return of an async function (ie Task) to a variable, when code execution reaches this line, it just continues past that line in the surrounding function while the Task executes asynchronously.

    0 讨论(0)
  • 2020-11-21 05:38

    Here is a quick console program to make it clear to those who follow. The TaskToDo method is your long running method that you want to make async. Making it run async is done by the TestAsync method. The test loops method just runs through the TaskToDo tasks and runs them async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace TestingAsync
    {
        class Program
        {
            static void Main(string[] args)
            {
                TestLoops();
                Console.Read();
            }
    
            private static async void TestLoops()
            {
                for (int i = 0; i < 100; i++)
                {
                    await TestAsync(i);
                }
            }
    
            private static Task TestAsync(int i)
            {
                return Task.Run(() => TaskToDo(i));
            }
    
            private async static void TaskToDo(int i)
            {
                await Task.Delay(10);
                Console.WriteLine(i);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:39

    is using them equal to spawning background threads to perform long duration logic?

    This article MDSN:Asynchronous Programming with async and await (C#) explains it explicitly:

    The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

    0 讨论(0)
提交回复
热议问题