在异步函数内部使用与外部不同的 SynchronizationContext 时,我的行为令人困惑。
我的大部分程序代码使用自定义 SynchronizationContext,它只是将 SendOrPostCallbacks 排队并在我的主线程中的特定已知点调用它们。我在开始时设置了这个自定义 SynchronizationContext,当我只使用这个时一切正常。
我遇到的问题是我有一些函数,我希望它们的等待继续在线程池中运行。
void BeginningOfTime() {
// MyCustomContext queues each endOrPostCallback and runs them all at a known point in the main thread.
SynchronizationContext.SetSynchronizationContext( new MyCustomContext() );
// ... later on in the code, wait on something, and it should continue inside
// the main thread where MyCustomContext runs everything that it has queued
int x = await SomeOtherFunction();
WeShouldBeInTheMainThreadNow(); // ********* this should run in the main thread
}
async int SomeOtherFunction() {
// Set a null SynchronizationContext because this function wants its continuations
// to run in the thread pool.
SynchronizationContext prevContext = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext( null );
try {
// I want the continuation for this to be posted to a thread pool
// thread, not MyCustomContext.
await Blah();
WeShouldBeInAThreadPoolThread(); // ********* this should run in a thread pool thread
} finally {
// Restore the previous SetSynchronizationContext.
SynchronizationContext.SetSynchronizationContext( prevContext );
}
}
我得到的行为是每次等待之后的代码都是在看似随机的线程中执行的。有时,WeShouldBeInTheMainThreadNow() 在线程池线程中运行,有时在主线程中运行。有时 WeShouldBeInAThreadPoolThread() 正在运行
我在这里看不到任何模式,但我认为无论 SynchronizationContext.Current 在您使用 await 的行设置为什么,都将定义 await 之后的代码将在何处执行。这是一个不正确的假设吗?如果是这样,是否有一种紧凑的方式来做我在这里想做的事情?