C# async/await strange behavior in console app

前端 未结 4 843
臣服心动
臣服心动 2021-01-17 22:33

I built some async/await demo console app and get strange result. Code:

class Program
{
    public static void BeginLongIO(Action act)
    {
        Console.         


        
4条回答
  •  温柔的废话
    2021-01-17 22:52

    This isn't how async-await works.

    Marking a method as async doesn't create any background threads. When you call an async method it runs synchronously until an asynchronous point and only then returns to the caller.

    That asynchronous point is when you await a task that haven't completed yet. When it does complete the rest of the method is scheduled to be executed. This task should represent an actual asynchronous operation (like I/O, or Task.Delay).

    In your code there is no asynchronous point, there's no point in which the calling thread is returned. The thread just goes deeper and deeper and blocks on Thread.Sleep until these methods are completed and DoAsync returns.

    Take this simple example:

    public static void Main()
    {
        MainAsync().Wait();
    }
    
    public async Task MainAsync()
    {
        // calling thread
        await Task.Delay(1000);
        // different ThreadPool thread
    }
    

    Here we have an actual asynchronous point (Task.Delay) the calling thread returns to Main and then blocks synchronously on the task. After a second the Task.Delay task is completed and the rest of the method is executed on a different ThreadPool thread.

    If instead of Task.Delay we would have used Thread.Sleep then it will all run on the same calling thread.

提交回复
热议问题