c# - 使用 CConfigureAwait(false) 时,为什么我有一个填充的 HttpContext?
问题描述
首先,我看到了这个问题:ConfigureAwait(false) not making HttpContext NULL as expected但我仍然无法解释发生了什么。
这里我有两种方法:
public async Task<ActionResult> Contact2()
{
var h = new HttpClient();
var sc = SynchronizationContext.Current;
HttpContext.Session["x"] = "d";
var s = await h.GetStringAsync("http://www.google.com").ConfigureAwait(false);
var contextIsNull = HttpContext == null;
return View();
}
public async Task<ActionResult> Contact()
{
var h = new HttpClient();
var sc = SynchronizationContext.Current;
HttpContext.Session["x"] = "d";
await Task.Delay(2000).ConfigureAwait(false);
var contextIsNull = HttpContext == null;
return View();
}
执行它们时,SynchronizationContext.Current
如预期的那样为 null,但HttpContext
不是 null 并且在这两种情况下我都可以访问Session
. 为什么是这样?为什么HttpContext
不为空?上下文已经切换,因为我HttpContext
在等待之后阅读,对吧?
解决方案
HttpContext.Current
是null
,不是Controller.HttpContext
。
await
不会更改任何本地或成员变量的值。
请注意,仅仅因为您可以访问它并不意味着您应该. HttpContext
不是线程安全的。
推荐阅读
- android - 错误:将linkedin插件添加到Ionic3时,包com.linkedin.platform不存在
- django - Django:`相关字段查找无效:icontains`
- spring-boot - Keycloak 弹簧适配器 - 检查 authToken 在每个 http 请求中是否处于活动状态
- java - 菜单未显示在操作栏上
- python-2.7 - 如何在pytest python中运行重复的测试步骤
- qt - 如何在 QML 中操作颜色
- logic - 逆在群论中的重要性
- android - Activity has leaked window DecorView@92f9f38[] that original is added here error
- java - 在 RestAssured JsonPath 的帮助下,我无法从下面的 json 中获取 id 列表
- r - R 通过 tolower 加入