首页 > 解决方案 > 使用 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在等待之后阅读,对吧?

标签: c#.netasp.net-mvcasync-await

解决方案


HttpContext.Currentnull,不是Controller.HttpContext

await不会更改任何本地或成员变量的值。

请注意,仅仅因为您可以访问它并不意味着您应该. HttpContext不是线程安全的。


推荐阅读