System.Web.HttpContext.Current nulls itself after

2019-06-21 22:33发布

I encountered a weird issue today which made no sense to me. Here is a summary:

Inside a method, I check for a cached item as below:

private async Task<RatesStatus> getRatesStatusAsync() {

    //...

    if (_currentHttpContext != null) {

        //Here, I am checking for a Cached item
        var cachedRatesStatusObj = HttpContext.Current.Cache[Constants.RATESSTATUS_CACHE_KEY_NAME];
        if (cachedRatesStatusObj != null)
            return (RatesStatus)cachedRatesStatusObj;
    }

    //...

    cacheRatesStatusObject(ratesStatus);

    //...
}

Here, the HttpContext.Current is not null as expected inside an ASP.NET application. Then, inside the cacheRatesStatusObject method, I check if HttpContext.Current is null or not as below:

private void cacheRatesStatusObject(RatesStatus ratesStatus) {

    //...

    //Seeing if HttpContext.Current is null or not first.
    //and it is null here...
    if (HttpContext.Current == null)
        return;

    //...
}

And it is null there. No idea what is happening here. Any thoughts?

3条回答
Luminary・发光体
2楼-- · 2019-06-21 22:52

It does not null itself.

The HttpContext is only stored in a 'thread static' way.

As suggested by the other answer, just pass the instance.

查看更多
迷人小祖宗
3楼-- · 2019-06-21 23:03

When you use async/await, the thread handling the request marks the request as incomplete and then returns to the ASP.NET thread pool. When the awaitable completes later, another thread is assigned to run the rest of the method, however HttpContext is not migrated across threads, that's why you get null reference when calling await method.

You can pass a reference of the HttpContext to the await method, something like this:

await cacheRatesStatusObject(HttpContext.Current,  ratesStatus);

However you should be very careful dealing with concurrency and race conditions, for example if the await thread locks a resource and another request thread attempts to use it then your thread pool goes boom. Most people resolve this by creating new objects and passing them into paramaterized threads instead of passing a reference of HttpContext across threads.

查看更多
Root(大扎)
4楼-- · 2019-06-21 23:04

Passing the instance sucks.

Use the .NET 4 MemoryCache classes instead.

http://stevescodingblog.co.uk/net4-caching-with-mvc/

查看更多
登录 后发表回答