当async-await改变线程?

时间:2017-04-19 14:17:48

标签: c# async-await

  • 当我调用test1()方法时,ManagedThreadId将在之后更改 延迟(1)。
  • 当我调用test2()方法(而不是test1())然后调用ManagedThreadId 会保持不变。

当async-await更改线程时?

在test2()方法中,完成方法所需的时间甚至比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 个答案:

答案 0 :(得分:6)

test1等待Task.Delay(1)将在等待它时完成,这意味着test1的其余部分需要安排为延续。

对于test2,您等待Task.FromResult,这将始终返回已完成的Task 。当await已经完成的任务时,该方法可以继续在当前线程上运行,而无需安排延续。