When async-await change thread?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-24 01:22:15

问题


  • When I call test1() method then ManagedThreadId will be changed after Delay(1).
  • When I call test2() method (instead of test1()) then ManagedThreadId will stay same.

When async-await change thread?

In test2() method time required to finish method is even longer then in test1()

    [Route("api/[controller]")]
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        await MainAsync();
        return new ObjectResult(null);
    }

    static async Task MainAsync()
    {
        Console.WriteLine("Main Async: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        await test1();
        //await test2();
        // . . .more code
    }

    private static async Task test1()
    {
        Console.WriteLine("thisIsAsyncStart: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        await Task.Delay(1);
        Console.WriteLine("thisIsAsyncEnd: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
    }

    private static async Task test2()
    {
        Console.WriteLine("thisIsAsyncStart: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        System.Threading.Thread.Sleep(5000);
        await Task.FromResult(0);
        Console.WriteLine("thisIsAsyncEnd: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
    }

回答1:


test1 awaits Task.Delay(1), which isn't going to be completed at the time it goes to await it, meaning the rest of test1 needs to be scheduled as a continuation.

For test2 you're awaiting Task.FromResult, which will always return an already completed Task. When you await an already completed task the method can just keep running on the current thread, without needing to schedule a continuation.



来源:https://stackoverflow.com/questions/43498365/when-async-await-change-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!