Execute task with the CurrentCulture set to the Task creator CurrentCulture

后端 未结 3 1629
无人共我
无人共我 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:45

    Im not sure you really need a MonitoredTask for this. You can capture the custom culture using closure:

    public static Task ExecuteTask(Action action, string name)
    {
       var customCulture = CustomCultureInfo.CurrentCulture;
       return Task.Factory.StartNew(() => 
       {
           // use customCulture variable as needed
          // inside the generated task.
       });
    }
    

    Another way of doing this would be to pass the current culture as object state using the proper overload (either Action or Func):

    public static Task ExecuteTask(Action action, string name)
    {
       var customCulture = CustomCultureInfo.CurrentCulture;
       return Task.Factory.StartNew((obj) => 
       {
           var culture = (CultureInfo) obj;
           // use customCulture variable as needed
          // inside the generated task.
       }, customCulture);
    }
    

    I would definitely go with the former.

    For more on closure, see What are 'closures' in .NET?

    提交回复
    热议问题