I have following pseudo-code
string GetData()
{
var steps = new List<Task<string>>
{
DoSomeStep(),
DoSomeStep2()
};
await Task.WhenAll(steps);
return SomeResourceManagerProxy.RetrieveValuesForLocalizedStrings( steps.Select(s => s.Result) );
}
This method is called from WebService, where I set Thread.CurrentUICulture
according to user's browser settings.
After await, the CurrentUICulture
is lost (I run on different thread).
I have solved the issue with following:
public class MyAwaiter<T> : INotifyCompletion
{
private TaskAwaiter<T> waiter;
private CultureInfo culture;
public MyAwaiter(TaskAwaiter<T> waiter)
{
this.waiter = waiter;
}
public PreserveCultureAwaiter<T> GetAwaiter() { return this; }
public bool IsCompleted { get { return waiter.IsCompleted; } }
public void OnCompleted(Action continuation)
{
culture = Thread.CurrentThread.CurrentUICulture;
waiter.OnCompleted(continuation);
}
public T GetResult()
{
Thread.CurrentThread.CurrentUICulture = culture;
return waiter.GetResult();
}
}
public static MyAwaiter<T> KeepCulture<T>(this Task<T> task)
{
return new MyAwaiter<T>(task.GetAwaiter());
}
...
await Task.WhenAll(steps).KeepCulture();
This has one drawback - need for remembering to call KeepCulture() on every task that is being awaited. (I have also some extension method to keep the UI culture in task).
Is there any easier way how to preserve UI culture?
OnCompleted
is never called. – Cooperation