2

嗨–我计划基于“Accept-Language”标头处理服务器端本地化的错误字符串等,方法是根据该标头设置 CurrentUICulture,但显然它不会流经异步调用,下面是示例代码来说明问题,是否有任何默认方式来处理异步调用的本地化?

   public async Task<HttpResponseMessage> GetAsync()
    {            
        //set the current ui culture, to say "fr-FR", based on "Accept-Language" header
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("**fr-FR**");  

       var task = httpClient.PutAsync(endpoint, content)            

        //do some processing

        var res  = await task;

        var culture = Thread.CurrentThread.CurrentUICulture.Name; **//ITS NOT necessarily fr-FR**

        //do some more processing
        //and handle localizations etc.

        return res;
    }

对于存在真正异步操作的情况,我正在寻找一种更清洁/无缝的本地化处理方式。对于等待调用之后的代码

编辑:为清楚起见,将 Task.Run() 替换为 httpClient.PutAsync

4

1 回答 1

2

Task.Run并且Task.Factory.StartNew没有任何上下文。这是预期的行为。使用await关键字时会保留上下文。所以这是你可以做的:

public static async Task<IEnumerable<string>> GetAsync()
{            
    //set the current ui culture, to say "fr-FR", based on "Accept-Language" header
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");

    //do some processing

    var s = await GetSomething();

    var culture = Thread.CurrentThread.CurrentUICulture.Name; //It's ja-JP

    return new[] { s, s };
}

public static Task<string> GetSomething()
{
    var cuture = Thread.CurrentThread.CurrentUICulture.Name; // It's fr-FR
    var tcs = new TaskCompletionSource<string>();
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("ja-JP");
    tcs.SetResult("<something>");
    return tcs.Task;
}
于 2012-12-31T09:09:46.387 回答