Search code examples
c#resx

ResX Autogenerated File for Culture Specific Access to Resources


Is there a way to auto generate a file that can perform thread safe, culture specific access to a resource? The current Resource.Designer.cs class being generated for my resx file by Visual Studio looks like:

    private static global::System.Resources.ResourceManager resourceMan;

    private static global::System.Globalization.CultureInfo resourceCulture;

    [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
    internal Resource()
    {
    }

    /// <summary>
    ///   Returns the cached ResourceManager instance used by this class.
    /// </summary>
    [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
    public static global::System.Resources.ResourceManager ResourceManager
    {
        get
        {
            if (object.ReferenceEquals(resourceMan, null))
            {
                global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ServiceModels.Resource", typeof(Resource).Assembly);
                resourceMan = temp;
            }
            return resourceMan;
        }
    }

    /// <summary>
    ///   Overrides the current thread's CurrentUICulture property for all
    ///   resource lookups using this strongly typed resource class.
    /// </summary>
    [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
    public static global::System.Globalization.CultureInfo Culture
    {
        get
        {
            return resourceCulture;
        }
        set
        {
            resourceCulture = value;
        }
    }

    /// <summary>
    ///   Looks up a localized string similar to Hiii.
    /// </summary>
    public static string Hello
    {
        get
        {
            return ResourceManager.GetString("Hello", resourceCulture);
        }
    }

This allows safe access to the "Hello" resource, but it doesn't appear to be thread safe when using different resource files of different cultures. For example, with this code, you would set the resource by

Culture = CultureInfo.SomeCulture;

This would set the culture for all threads using the ResourceManager. Is there a way to auto generate a file that allows thread safe, culture specific access to a resource or do I have to implement one myself?


Solution

  • Thread.CurrentThread.CurrentCulture is a thread specific Culture setting that most of the library uses for things like formatting date/times or numbers and in your case for getting translated strings.

    https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.currentculture?view=netframework-4.8