Async call to the WCF service doesn't preserve CurrentCulture

后端 未结 2 1247
失恋的感觉
失恋的感觉 2020-12-06 14:02

According to the answer in this question async/await call should preserve CurrentCulture. In my case, when I call my own async methods, the CurrentCulture is pr

2条回答
  •  星月不相逢
    2020-12-06 14:22

    I don't have a definitive answer on why the described behavior may take place, especially given the statement that the whole chain of calls stay on the same thread (ManagedThreadId remains the same). Moreover, my assumption that culture doesn't flow with the execution context under AspNetSynchronizationContext was wrong, it does flow, in fact. I took the point from @StephenCleary's comment about trying await Task.Delay and verified that with the following little research:

    // GET api/values/5
    public async Task Get(int id)
    {
        // my default culture is en-US
        Log("Get, enter");
    
        Thread.CurrentThread.CurrentCulture = new CultureInfo("hu-HU");
    
        Log("Get, before Task.Delay");
        await Task.Delay(200);
        Thread.Sleep(200);
    
        Log("Get, before Task.Run");
        await Task.Run(() => Thread.Sleep(100));
        Thread.Sleep(200);
    
        Log("Get, before Task.Yield");
        await Task.Yield();
    
        Log("Get, before exit");
        return "value";
    }
    
    static void Log(string message)
    {
        var ctx = SynchronizationContext.Current;
        Debug.Print("{0}; thread: {1}, context: {2}, culture {3}",
            message,
            Thread.CurrentThread.ManagedThreadId,
            ctx != null ? ctx.GetType().Name : String.Empty,
            Thread.CurrentThread.CurrentCulture.Name);
    }
    

    Output:

    Get, enter; thread: 12, context: AspNetSynchronizationContext, culture en-US
    Get, before Task.Delay; thread: 12, context: AspNetSynchronizationContext, culture hu-HU
    Get, before Task.Run; thread: 11, context: AspNetSynchronizationContext, culture hu-HU
    Get, before Task.Yield; thread: 10, context: AspNetSynchronizationContext, culture hu-HU
    Get, before exit; thread: 11, context: AspNetSynchronizationContext, culture hu-HU
    

    Thus, I could only imagine something inside wcfClient.GetResultAsync() actually changes the current thread's culture. A workaround for this could be to use a customer awaiter like Stephen Toub's CultureAwaiter. However, this symptom is worrying. Maybe you should search the generated WCF client proxy code for "culture" and check what's going on in there. Try stepping it through and find out at what point Thread.CurrentThread.CurrentCulture gets reset.

提交回复
热议问题