lock Thread.CurrentThread.CurrentUICulture

96 Views Asked by At

I've a method that runs an action with a specific CurrentUICulture and at the end it rolls back to the original CurrentUICulture. Here's the snippet

    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 is temporary changed in different parts of my project.

The problem is that sometimes "action()" does not run with the temporary setted CurrentUICulture passed to "ExecuteInLanguage", but with other languages, probably because CurrentUICulture is changed in the same time somewhere else.

Could using "lock" be the correct solution to avoid the described?

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

There are 0 best solutions below