在下面的代码片段中,
SynchronizationContext
被丢失了,因此也丢失了CurrentCulture
和CurrentUICulture
。 Log()
来自于这个答案。public async Task<ActionResult> Index()
{
Log("before GetAsync");
await new HttpClient().GetAsync("http://www.example.com/")
.ContinueWith(request =>
{
Log("ContinueWith");
request.Result.EnsureSuccessStatusCode();
}, TaskContinuationOptions.AttachedToParent);
return View();
}
static void Log(string message)
{
var ctx = System.Threading.SynchronizationContext.Current;
System.Diagnostics.Debug.Print("{0}; thread: {1}, context: {2}, culture: {3}, uiculture: {4}",
message,
System.Threading.Thread.CurrentThread.ManagedThreadId,
ctx != null ? ctx.GetType().Name : String.Empty,
System.Threading.Thread.CurrentThread.CurrentCulture.Name,
System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
}
以下是输出内容:
在执行 GetAsync 之前,线程:56,上下文:AspNetSynchronizationContext,区域设置:nl,UI 区域设置:nl
ContinueWith;线程:46,上下文:,区域设置:nl-BE,UI 区域设置:en-US
在执行 GetAsync
之前,区域设置和 UI 区域设置的值是我在 Application_BeginRequest
中设定的。但是在 ContinueWith
中,上下文丢失了,区域设置被设置为浏览器提供的值,UI 区域设置被设置为默认值。
按照我的理解,所有涉及到 AspNetSynchronizationContext
的操作都应该自动完成。我的代码有什么问题呢?
ContinueWith
和TaskContinuationOptions.AttachedToParent
吗?请查看 这里,以确保TaskContinuationOptions.AttachedToParent
可以给你想要的行为。 - noseratio - open to workContinueWith
是否更好?这让我感觉自己毫无理由地陷入了困境。简而言之,我正在进行Web API请求,反序列化响应并执行回调。 - user247702ContinueWith
。为什么不能只使用async/await
呢? - noseratio - open to workasync
,我猜在我们的尝试中,我们发现ContinueWith
(表面上)可行,所以我们最终保留了那段代码。我会尝试重写调用,感谢您的建议。 - user247702