将CurrentCulture设置为任务创建者CurrentCulture来执行任务 [英] Execute task with the CurrentCulture set to the Task creator CurrentCulture

查看:67
本文介绍了将CurrentCulture设置为任务创建者CurrentCulture来执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用任务"的应用程序.我们还修改了cultureInfo(我们使用EN-US语言,但保留了日期/数字格式),并使用了.Net 4.0.

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 application has a lot of thread and task, and we have a factory for the creation of Task/Threads.

对于该线程,我们具有以下代码,以确保每个线程都使用正确的CurrentCulture启动:

For the thread, we have the following code, to ensure that every thread is launched with the correct CurrentCulture:

//This is basically only the constructor, but it describe well how we create the Thread:
public MonitoredThread(ThreadStart threadStart, string name, bool isBackground = false)
{
    m_threadStart = threadStart;
    m_name = name;
    m_isBackground = isBackground;
    Thread = new Thread(ThreadWorker)
    {
        Name = name,
        IsBackground = isBackground,
        CurrentCulture = CustomCultureInfo.CurrentCulture,
        CurrentUICulture = CustomCultureInfo.CurrentCulture
    };
}

但是对于Tasks,我不知道如何实现这种机制:

But for the Tasks, I don't know how to implement this kind of mechanism:

public static Task ExecuteTask(Action action, string name)
{
    MonitoredTask task = new MonitoredTask(action, name);
    return Task.Factory.StartNew(task.TaskWorker);
}

有什么主意吗?

推荐答案

我不确定您是否真的需要MonitoredTask.您可以使用闭包捕获自定义区域性:

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.
   });
}

另一种方法是使用适当的重载(Action<object>Func<object, TResult>)将当前区域性作为object state传递:

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

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);
}

我肯定会选择前者.

有关关闭的更多信息,请参见 .NET中的关闭"是什么?

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

这篇关于将CurrentCulture设置为任务创建者CurrentCulture来执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆