gpt4 book ai didi

c# - 等待不使用当前的 SynchronizationContext

转载 作者:太空狗 更新时间:2023-10-30 01:35:21 26 4
gpt4 key购买 nike

在异步函数内部使用与外部不同的 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 之后的代码将在何处执行。这是一个错误的假设吗?如果是这样,是否有一种紧凑的方法来完成我在这里尝试做的事情?

最佳答案

我希望您的代码能够工作,但有几个可能的原因导致它不能工作:

  1. 确保您的 SynchronizationContext 在执行其延续时是最新的。
  2. 没有严格定义 何时 SynchronizationContext 被捕获。
  3. SynchronizationContext 中运行代码的正常方法是在一个方法中建立当前的一对一方法,然后运行依赖它的另一个(可能是异步的)方法。
  4. 避免当前 SynchronizationContext 的正常方法是将 ConfigureAwait(false) 附加到所有等待的任务。

关于c# - 等待不使用当前的 SynchronizationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227566/

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