问题
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?
回答1:
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.
回答2:
Passing the instance sucks.
Use the .NET 4 MemoryCache classes instead.
http://stevescodingblog.co.uk/net4-caching-with-mvc/
回答3:
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.
来源:https://stackoverflow.com/questions/10553907/system-web-httpcontext-current-nulls-itself-after-checking-for-a-cache