gpt4 book ai didi

c# - 异步等待何时更改线程?

转载 作者:行者123 更新时间:2023-12-05 09:18:47 25 4
gpt4 key购买 nike

  • 当我调用 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());
}

最佳答案

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

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

关于c# - 异步等待何时更改线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com