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?
It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread. Task supports cancellation through the use of cancellation tokens.
Differences Between Task And ThreadThe Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.
NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR.
To change the current UI culture, you assign the CultureInfo object that represents the new UI culture to the Thread. CurrentThread. CurrentUICulture property.
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
.
Otherwise, AspNetSynchronizationContext
will correctly flow CurrentCulture
across await
continuations, even though they happen on different threads.
In short, yes ASP.NET is configured to flow things like culture across your asynchronous operations via a SynchronizationContext
. You can read a bit about how it works on MSDN: https://msdn.microsoft.com/en-us/magazine/gg598924.aspx
There are some gotchas related to identity that you can read about on this SO question: Using ASP.NET Web API, my ExecutionContext isn't flowing in async actions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With