将CurrentUICulture传递给ASP.NET MVC 3.0中的异步任务

Lin*_*eed 5 asp.net-mvc asynchronous cultureinfo task-parallel-library

活动语言是从URL确定的,然后设置在

Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
Run Code Online (Sandbox Code Playgroud)

这样,从正确的资源文件中检索翻译.

在控制器上使用Async操作时,我们有一个后台线程,其中Thread.CurrentThread.CurrentUICulture设置回操作系统默认值.但是在后台线程中我们需要正确的语言.

我创建了一个TaskFactory扩展来将文化传递给后台线程,它看起来像这样:

public static Task StartNew(this TaskFactory taskFactory, Action action, CultureInfo cultureInfo)
{
    return taskFactory.StartNew(() =>
    {
         Thread.CurrentThread.CurrentUICulture = cultureInfo;
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);

         action.Invoke();
     });
}
Run Code Online (Sandbox Code Playgroud)

这允许我在动作控制器中执行以下操作:

 [HttpPost]
 public void SearchAsync(ViewModel viewModel)
 {
     AsyncManager.OutstandingOperations.Increment();
     AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
     {
         try
         {
               //Do Stuff
               AsyncManager.Parameters["viewModel"] = viewModel;
         }
         catch (Exception e)
         {
             ModelState.AddModelError(string.Empty, ResxErrors.TechnicalErrorMessage);
         }
         finally
         {
             AsyncManager.OutstandingOperations.Decrement();
         }
     }, Thread.CurrentThread.CurrentUICulture);
 }



 public ActionResult SearchCompleted(Task task, ViewModel viewModel)
 {
     //Wait for the main parent task to complete. Mainly to catch all exceptions.
     try { task.Wait(); }
     catch (AggregateException ae) { throw ae.InnerException; }

     return View(viewModel);
 }
Run Code Online (Sandbox Code Playgroud)

这一切都很完美,但我确实有一些顾虑.

这是通过在调用原始操作之前设置文化来扩展操作的正确方法吗?

有没有人知道将te CurrentUICulture传递给ASP.NET MVC异步操作的后台线程的不同方法?

  • 会话不是一个选项.
  • 我确实在考虑使用CallContext.

对此代码有何评论?

谢谢

Lin*_*eed 1

看来问题中描述的方式就是答案。