【发布时间】:2022-01-04 22:49:43
【问题描述】:
我正在尝试理解async/await 并阅读AsyncMethodBuilder 的源代码。我认为必须有一些代码,例如 xxx.Wait() 或 xxx.WaitOnce() 等待任务完成。
但是,我在 AsyncMethodBuilder 类中没有找到这样的代码。
系统\运行时\compilerservices\AsyncMethodBuilder.cs https://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs,96
于是我一直在挖掘,试图阅读Task、TaskScheduler、ThreadPoolTaskScheduler、ThreadPool的源代码。
最后我得到了_ThreadPoolWaitCallback 的课程,但没有找到任何来电者。
https://referencesource.microsoft.com/#mscorlib/system/threading/threadpool.cs,d7b8a78b4dd14fd0
internal static class _ThreadPoolWaitCallback
{
[System.Security.SecurityCritical]
static internal bool PerformWaitCallback()
{
return ThreadPoolWorkQueue.Dispatch();
}
}
另一个可能的代码在类SynchronizationContext,方法SetWaitNotificationRequired()
protected void SetWaitNotificationRequired()
{
...
RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait));
...
但是我不知道RuntimeHelpers.PrepareDelegate在做什么,这是一个native方法。
请给点建议。有Wait 吗?如果是,它在哪里?
【问题讨论】:
-
所以您希望some thread 在等待
Task期间被阻止? -
我不太明白这个问题,但如果它有任何用处 - C# 编译器将 async/await 重写为状态机(它实际上只是一个 switch 语句),然后它将重复调用基于事件的方式。没有阻塞的线程/线程可以再次唤醒。
-
@LukeBriggs 是的,希望 OP 能够更清楚地说明他们的要求。问题似乎是“
Wait在哪里?”,它假设某处有一个Wait。恕我直言,更好的问题是“有Wait吗?如果有,它在哪里?” -
@TheodorZoulias 是的,你是对的。我的问题正是你所说的。有
Wait吗?如果是,它在哪里? -
@Dai 我认为你是对的。非常感谢
标签: c# async-await