How to ensure different CultureInfo.CurrentCulture for calls to specific library

96 Views Asked by At

I have a 3rd party library that uses CultureInfo.CurrentCulture but it must be set to InvariantCulture to function properly.

My multithreaded application uses localized CultureInfo.CurrentCulture.

public string WrappedCallTo3rdPartyLibrary(string input)
{
    //use new thread to isolate CurrentCulture side effects.
    return Task.Factory.StartNew(() =>
    {
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
        string result = _3rdPartyLibrary.SynchronousCall(input);
        return result;
    }).GetAwaiter().GetResult();
}
  1. Is this proper way to set culture info for _3rdPartyLibrary?
  2. Do I have a guarantee that the above approach does not affect the parent thread?

EDIT:

I originally tried synchronous call, but I suspect it had side effects (parent or previously started child threads affected?)

public string WrappedCallTo3rdPartyLibrary(string input)
{
    var ciBackup = CultureInfo.CurrentCulture;
    try
    {
       CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
       return _3rdPartyLibrary.SynchronousCall(input);
    }
    finally
    { 
        CultureInfo.CurrentCulture = ciBackup ;
    }
}
1

There are 1 best solutions below

4
Nick On

The synchronous call you suggest should not have side effects even if it is executed on the thread pool, i.e. in a task.

As a side note, you should avoid Task.GetAwaiter().GetResult();. Better use Task.Wait() and Task.Result.

UPDATE

Let me quote the documentation:

This method is intended for compiler use rather than use directly in code.