我有一种方法可以使用特定的 CurrentUICulture 运行操作,最后它会回滚到原始的 CurrentUICulture。这是片段
private static void ExecuteInLanguage(string language, Action action)
{
var current = Thread.CurrentThread.CurrentUICulture;
try
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
action();
}
finally
{
Thread.CurrentThread.CurrentUICulture = current;
}
}
CurrentUICulture 在我项目的不同部分临时更改。
问题是有时“action()”不会在临时设置的 CurrentUICulture 传递给“ExecuteInLanguage”的情况下运行,而是在其他语言中运行,可能是因为 CurrentUICulture 在其他地方同时更改。
使用“锁定”可以避免所描述的正确解决方案吗?
private static void ExecuteInLanguage(string language, Action action)
{
var current = Thread.CurrentThread.CurrentUICulture;
try
{
lock (Thread.CurrentThread.CurrentUICulture)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
action();
}
}
finally
{
Thread.CurrentThread.CurrentUICulture = current;
}
}