问题描述
限时送ChatGPT账号..请考虑以下代码
public static async Task<int> Answer()
{
await Task.Delay(1000);
return 42;
}
static void Main(string[] args)
{
for (int j = 0; j < 20; j++)
{
Console.WriteLine(j +" " + Thread.CurrentThread.IsThreadPoolThread);
if (j == 1)
{
new Task( async ()=>
{
int answer = await Answer();
Console.WriteLine(answer + " " + Thread.CurrentThread.IsThreadPoolThread);
}).Start();
}
Thread.Sleep(200);
}
return;
你能猜出打印答案时的CurrentThread.IsThreadPoolThread
是什么吗?
Can you guess what the CurrentThread.IsThreadPoolThread
when printing answer is?
看来 Task.Delay(..)
正在这样做,因为如果我删除 await,那么答案是 False
.但是,我似乎找不到 Delay
实际上在文档中将内容放在线程池中.
It appears that Task.Delay(..)
is doing it, for if I remove await, then the answer is False
. However, I can not seem to find that Delay
actually puts stuff on the thread pool in the documentation.
这让我想到了一个更普遍的问题.除了Run(..)
之外,Task实际上启动了一个线程池线程做什么?
This brings me to the more general question. What in Task does actually start up a thread pool thread besides Run(..)
?
用 Ask()
public static async void Ask()
{
int answer = await Answer();
Console.WriteLine(answer + " " + Thread.CurrentThread.IsThreadPoolThread);
}
产生相同的结果
推荐答案
正如我在我的 async
/await
intro 帖子,默认情况下 await
将捕获当前的上下文"并将其用于执行延续(await
之后的代码).这个上下文"是 SynchronizationContext.Current
,除非它是 null
,在这种情况下它是 TaskScheduler.Current
.
As I describe in my async
/ await
intro post, by default await
will capture the current "context" and use that to execute the continuation (the code after the await
). This "context" is SynchronizationContext.Current
unless it is null
, in which case it is TaskScheduler.Current
.
我还描述了 在控制台上使用 async
应用在我的博客上.控制台应用程序不提供 SynchronizationContext
,因此上下文"回退到 TaskScheduler.Current
.由于当前执行的Task
运行在线程池上,TaskScheduler.Current
与TaskScheduler.Default
相同,即线程池任务调度器.
I also describe using async
on Console apps on my blog. Console apps do not provide a SynchronizationContext
, so the "context" falls back to TaskScheduler.Current
. Since the currently-executing Task
is running on the thread pool, TaskScheduler.Current
is the same as TaskScheduler.Default
, which is the thread pool task scheduler.
这就是您的代码在线程池线程上恢复的原因.这是正确的行为.
This is why your code is resuming on a thread pool thread. It's the correct behavior.
这篇关于使用 async/await 时,Task 中的线程池线程会放什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论