传递的CurrentUICulture以异步任务在ASP.NET MVC 3.0 [英] Pass CurrentUICulture to Async Task in ASP.NET MVC 3.0
问题描述
主动语言从URL来确定,然后设置
The active language is determined from the url and then set on the
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
翻译是从正确的资源文件中检索的方式。
That way the translations are retrieved from the correct resource files.
当使用控制器的异步操作,我们有一个后台线程,其中Thread.CurrentThread.CurrentUICulture重新设置为默认的操作系统。同时也对后台线程,我们需要正确的语言。
When using Async action on controllers, we have a background thread, where the Thread.CurrentThread.CurrentUICulture is set back to OS default. But also on the background thread we need the correct language.
我创建了一个TaskFactory延伸至文化传递给后台线程,它看起来是这样的:
I created a TaskFactory extension to pass the culture to the background thread and it 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);
}
这所有的作品完美,但我确实有一些顾虑。
This all works perfectly, but I do have some concerns.
这是通过调用原有的动作之前设置的文化来扩展动作的正确方法?
Is this the correct way to extend an action by setting the culture before invoking the original action ?
有谁知道不同的方式来德的CurrentUICulture传递给后台线程ASP.NET MVC的异步操作?
Does anyone know of a different way to pass te CurrentUICulture to a background thread for ASP.NET MVC Async actions ?
- 会话不是一个选项。
- 我想使用的CallContext中。
在这个$ C $(c)任何其他意见?
Any other comments on this code ?
感谢
推荐答案
这似乎在这个问题所描述的方式就是答案。
It seems the described way in the question is the answer.
这篇关于传递的CurrentUICulture以异步任务在ASP.NET MVC 3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!