System.Web.HttpContext.Current空本身对用户进行缓存后 [英] System.Web.HttpContext.Current nulls itself after checking for a Cache

查看:166
本文介绍了System.Web.HttpContext.Current空本身对用户进行缓存后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天做没有意义的我遇到了一个奇怪的问题。这里是一个总结:

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);

    //...
}

在这里, HttpContext.Current 如预期的ASP.NET应用程序中不为空。然后, cacheRatesStatusObject 方法里面,我检查 HttpContext.Current 为空或不是如下:

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?

推荐答案

当您使用异步/的await,线程处理请求,标志着该请求不完整,然后返回到 ASP.NET线程池。当awaitable完成后,另一个线程分配给运行的方法的其余部分,但HttpContext的不跨线程迁移,这就是为什么你在调用await方法时,你得到空引用。

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.

您可以传递的HttpContext的参考await方法,是这样的:

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

await cacheRatesStatusObject(HttpContext.Current,  ratesStatus);

但是,如果线程的await锁定资源,另一个请求线程试图使用它,然后你的线程池去热潮,你应该非常小心处理并发和比赛条件,例如。大多数人通过创建新的对象,并将其传递到paramaterized线程而不是线程之间传递的HttpContext的参考解决这个问题。

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.

这篇关于System.Web.HttpContext.Current空本身对用户进行缓存后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆