本文介绍了为什么HttpContext.Current空的await后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下测试的WebAPI code,我没有在生产中使用的WebAPI,但我做了,因为讨论我对这个问题的:的

I have the following test WebAPI code, I don't use WebAPI in production but I made this because of a discussion I had on this question: WebAPI Async question

不管怎么说,这里是违规的WebAPI方式:

Anyways, here's the offending WebAPI method:

public async Task<string> Get(int id)
{
    var x = HttpContext.Current;
    if (x == null)
    {
        // not thrown
        throw new ArgumentException("HttpContext.Current is null");
    }

    await Task.Run(() => { Task.Delay(500); id = 3; });

    x = HttpContext.Current;
    if (x == null)
    {
        // thrown
        throw new ArgumentException("HttpContext.Current is null");
    }

    return "value";
}

我附上认为,第二异常是预期的,因为的await完成时,它可能会在不同的线程,其中HttpContext.Current作为一个线程静态变量将不再解析为相应的值。现在的基础上,同步情况下,它实际上会被迫回到同一个线程中的await后,但我没有做任何事情在我的测试看中。这只是一个简单的,天真的使用等待

在另一个问题的意见有人告诉我,HttpContext.Current应在的await后解决。甚至还有另一显示同一对这个问题发表评论。那么什么是真的?它应该解决?我认为没有,但我想异步和等待够新,我不能在这一个权威的答案,因为发现什么决定性的。

In comments in another question I was told that HttpContext.Current should resolve after an await. There's even another comment on this question indicating the same. So what's true? Should it resolve? I think no, but I want an authoritative answer on this because async and await is new enough that I can't find anything definitive.

TL; DR:是HttpContext.Current可能为null一个的await后

TL;DR: Is HttpContext.Current potentially null after an await?

推荐答案

请确保你正在写一个ASP.NET的 4.5 的应用和定位4.5。 异步等待,除非你是在4.5上运行的,并已对未定义行为的ASP.NET 的使用新的任务型同步上下文。

Please ensure you are writing an ASP.NET 4.5 application, and targeting 4.5. async and await have undefined behavior on ASP.NET unless you are running on 4.5 and are using the new "task-friendly" synchronization context.

在特定的,这意味着你必须:

In particular, this means you must either:


  • 设置 httpRuntime.targetFramework 4.5

  • 的appSettings ,设置 ASPNET:UseTaskFriendlySynchronizationContext 真正

  • Set httpRuntime.targetFramework to 4.5, or
  • In your appSettings, set aspnet:UseTaskFriendlySynchronizationContext to true.

更多信息available这里。

这篇关于为什么HttpContext.Current空的await后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:06