异步和线程文化 [英] Asynchrony and thread culture
问题描述
我有一个MVC应用程序,我重写我的基本控制器的 OnActionExecuting()
方法来设置我的线程的文化:
I have an MVC app where I override my base controller's OnActionExecuting()
method to set my thread culture:
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
var langCode = GetLangCode();
Thread.CurrentThread.CurrentUICulture = new CultureInfo(langCode);
Thread.CurrentThread.CurrentCulture = new CultureInfo(langCode);
}
正如我开始异步编程更多,我很好奇如何,如果我们回到它的文化,我们已经修改到线程池线程文化是坚持和异步任务完成时一个新线程被分派?任何陷阱,我应该知道的?
As I have started to program asynchronously more, I'm curious about how culture is persisted if we return the thread whose culture we've modified to the thread pool, and a new thread is dispatched when the async task completes? Any gotchas I should be aware of?
推荐答案
一个重大的疑难杂症可能会使用伺机task.ConfigureAwait(假)
模式,它常常被误用作为一种简单(但错误)的补救措施针对死锁。通过这种方式,继续将上一个线程池没有发生同步上下文。在这种情况下,的CurrentCulture
将不会流动,因为<一href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/06/15/executioncontext-vs-synchronizationcontext.aspx\"相对=nofollow>它不会流入为的ExecutionContext
的一部分。更糟的是,你可能会使用 Task.Run(拉姆达)
(通常你不应该在ASP.NET应用程序)。里面的code 的λ
将不会有正确的的CurrentCulture
。
A major gotcha might be using the await task.ConfigureAwait(false)
pattern, which is often misused as an easy (but wrong) remedy against deadlocks. This way, the continuation would happen on a pool thread without synchronization context. In this case, CurrentCulture
won't be flowed, because it doesn't get flowed as a part of ExecutionContext
. Even worse, you might be using Task.Run(lambda)
(which normally you shouldn't in an ASP.NET application). The code inside lambda
will not have the correct CurrentCulture
.
另外, AspNetSynchronizationContext
将正确流动的CurrentCulture
横渡等待
延续,即使它们发生在不同的线程。
Otherwise, AspNetSynchronizationContext
will correctly flow CurrentCulture
across await
continuations, even though they happen on different threads.
这篇关于异步和线程文化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!