Execute task with the CurrentCulture set to the Task creator CurrentCulture

后端 未结 3 1622
无人共我
无人共我 2020-12-20 19:06

I\'ve an application where we use Tasks. We also modified the cultureInfo(we use the EN-US language, but keep the date/number format), and we use .Net 4.0.

The appli

3条回答
  •  独厮守ぢ
    2020-12-20 19:47

    Just to add some more detail to @Yuval Itzchakov answer, I normally create some extension methods for the TaskFactory class that preserve the Culture (I normally also add one that receives an action that sets any given property to the executing thread:

    #region StartNewWithPersistedCulture methods
    
    public static Task StartNewWithPersistedCulture(
        this TaskFactory taskFactory, Func function, CancellationToken cancellationToken = default (CancellationToken), TaskCreationOptions creationOptions = default (TaskCreationOptions))
    {
        if (taskFactory == null) throw new ArgumentNullException("taskFactory");
        if (function == null) throw new ArgumentNullException("function");
    
        var currentCulture = Thread.CurrentThread.CurrentCulture;
        var currentUICulture = Thread.CurrentThread.CurrentUICulture;
        return taskFactory.StartNew(
            () =>
            {
                Thread.CurrentThread.CurrentCulture = currentCulture;
                Thread.CurrentThread.CurrentUICulture = currentUICulture;
    
                return function();
            }, cancellationToken, creationOptions, TaskScheduler.Default);
    }
    
    public static Task StartNewWithPersistedCulture(
        this TaskFactory taskFactory, Action action, CancellationToken cancellationToken = default (CancellationToken), TaskCreationOptions creationOptions = default (TaskCreationOptions))
    {
        if (taskFactory == null) throw new ArgumentNullException("taskFactory");
        if (action == null) throw new ArgumentNullException("action");
    
        var currentCulture = Thread.CurrentThread.CurrentCulture;
        var currentUICulture = Thread.CurrentThread.CurrentUICulture;
        return taskFactory.StartNew(
            () =>
            {
                Thread.CurrentThread.CurrentCulture = currentCulture;
                Thread.CurrentThread.CurrentUICulture = currentUICulture;
    
                action();
            }, cancellationToken, creationOptions, TaskScheduler.Default);
    } 
    
    #endregion
    

提交回复
热议问题