Passing CurrentUICulture for Async Task to ASP.NET MVC 3.0

The active language is determined by the URL and then set to

Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);

Thus, translations are extracted from the correct resource files.

When using the Async action on the controllers, we have a background thread where Thread.CurrentThread.CurrentUICulture returns to the OS by default. But also in the background thread, we need the right language.

I created the TaskFactory extension to pass the culture to the background thread, and looks like this:

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

This allows me to do the following in an action controller:

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

It all works fine, but I have some problems.

Is this the right way to extend the action by establishing a culture before starting the original action?

- te CurrentUICulture ASP.NET MVC Async?

  • .
  • CallContext.

?

+5
1

, - .

+1

All Articles