gpt4 book ai didi

c# - SynchronizationContext,什么时候流什么时候不流?

转载 作者:太空狗 更新时间:2023-10-29 21:39:05 28 4
gpt4 key购买 nike

我正在尝试了解 SynchronizationContext 和 friend 。如果我在例如开始时设置自定义同步上下文控制台应用程序。在什么情况下当前同步上下文将与我的异步操作一起流动?Task 和其他的有区别吗? Delegate.BeginInvoke ?

void Main()
{
SynchronizationContext.SetSynchronizationContext(new FooContext());
Action a = () =>
{
var current = SynchronizationContext.Current;
//current is null here
};
a.BeginInvoke(null,null);

...sleep

如果我在线程池上执行任务,我是否被迫将同步上下文分配给当前正在执行我的工作的特定线程?

最佳答案

Under what conditions will the current synchronization context flow with my async operations?

async 方法执行 await 时,默认情况下它将捕获当前上下文并使用它来恢复 async 方法。此上下文为 SynchronizationContext.Current,除非它为 null,在这种情况下为 TaskScheduler.Current。我在我的 async intro blog post 中描述了这种行为, 我的 MSDN article on SynchronizationContext ,还有我的 MSDN article on async best practices .

Are there differences between Task and others, e.g. Delegate.BeginInvoke?

此行为是 asyncawait 所独有的。 Delegate.BeginInvoke 表示“在线程池线程上运行此委托(delegate)”,因此它不会传播 SynchronizationContextTask.Run 等更现代的方法也不行。

If I execute stuff on the thread pool, am I forced to assign a synchronization context to that specific thread that is currently executing my work?

一般来说,您不应该在不属于您的线程上安装同步上下文。如果确实在线程池线程上放置了一个,则应在线程返回到线程池之前将其删除。更有可能的是,如果您要安装同步上下文,则永远不应该返回线程(自定义同步上下文通常与该线程的“主循环”相关联)。

in the example above, logical call context flows but not synchronization context. any pointers to why this is the case would be interesting.

其他上下文的记录更少。 Stephen Toub 拥有 definitive post on the subject .本质上,某些数据(例如安全性)必须流动;大多数其他数据没有。

关于c# - SynchronizationContext,什么时候流什么时候不流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27229107/

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