Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As Joe pointed out, culture is transferred by the <code>HttpContext</code> in ASP.NET. The way ASP.NET does this is by installing a <code>SynchronizationContext</code> when a request starts, and that context is also used to resume asynchronous methods (by default).</p> <p>So, there are a couple of ways to approach the problem: you can either write your own <code>SynchronizationContext</code> that will preserve culture by default, or you can explicitly preserve the culture across each <code>await</code>.</p> <p>To preserve the culture at each <code>await</code>, you can use code <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115642.aspx">from Stephen Toub</a>:</p> <pre><code>public static CultureAwaiter WithCulture(this Task task) { return new CultureAwaiter(task); } public class CultureAwaiter : INotifyCompletion { private readonly TaskAwaiter m_awaiter; private CultureInfo m_culture; public CultureAwaiter(Task task) { if (task == null) throw new ArgumentNullException("task"); m_awaiter = task.GetAwaiter(); } public CultureAwaiter GetAwaiter() { return this; } public bool IsCompleted { get { return m_awaiter.IsCompleted; } } public void OnCompleted(Action continuation) { m_culture = Thread.CurrentThread.CurentCulture; m_awaiter.OnCompleted(continuation); } public void GetResult() { Thread.CurrentThread.CurrentCulture = m_culture; m_awaiter.GetResult(); } } </code></pre> <p>The <code>SynchronizationContext</code> approach is more complicated but once it's set up, it will be easier to use. I don't know of a good example of an ASP.NET-like context, but a good starting point is <a href="http://msdn.microsoft.com/en-us/magazine/gg598924.aspx">my MSDN article</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload