HttpContext类和它的线程安全 [英] HttpContext Class and its Thread Safety

查看:289
本文介绍了HttpContext类和它的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个辛格尔顿对象的应用程序,具有以下属性:

I have an Singleton object in application that has following property:

private AllocationActionsCollection AllocationActions
{
    get
    {
        return HttpContext.Current.Session["AllocationOptions.AllocationActions"] as AllocationActionsCollection;
    }
    set
    {
        HttpContext.Current.Session["AllocationOptions.AllocationActions"] = value;
    }
}

我处理一个错误( HttpContext.Current.Session [AllocationOptions.AllocationActions]为空,即使它应该是我总是被设置为有效的实例......)。我只是在MSDN阅读的HttpContext 实例成员不能保证是线程安全的!我不知道这可能是问题。有可能是一个资源比赛某处应用和时刻, HttpContext.Current.Session [AllocationOptions.AllocationActions]为空是AllocationActions二传手使用该语句中使用的时刻:

I'm dealing with one error (HttpContext.Current.Session["AllocationOptions.AllocationActions"] is null even though it is supposed to me always set to valid instance...). I just read in MSDN that HttpContext instance member are not guaranteed to be thread safe! I wonder if that could be the issue. There could be a resources race somewhere in application and the moment where HttpContext.Current.Session["AllocationOptions.AllocationActions"] is null is the moment where AllocationActions setter is used using this statement:

AllocationActions = new AllocationActionsCollection(Instance.CacheId);

我的问题是:

A)我很震惊,HttpContext.Current.Session不是线程安全的。如何安全地使用该财产呢?
b)你有任何想法,为什么Session变量可以为空(即使我pretty肯定,我将它设置它的使用在第一次之前)?

a) I'm shocked that HttpContext.Current.Session is not thread safe. How to safely use that property then? b) do you have any ideas why that Session variable can be null (even though I'm pretty sure I'm setting it before it's used for the first time)?

谢谢你,帕维尔

编辑1:

a)在初始化会话变量设置,每2分钟以下语句(在Page_Load中执行)行

a) line that initializes session variable is set every 2 minutes with following statement (executed in Page_Load)

AllocationActions = new AllocationActionsCollection(Instance.CacheId);

B)code调用,调用getter时在事件处理程序(如Button_Click)

b) code that calls getter is called in event handlers (like Button_Click)

c)由于应用没有自定义线程。唯一共同的HTTP处理程序

c) there is not custom threading in application. only common HTTP Handler

推荐答案

A 对象是通过限制一个类的实例化一个对象实现。

A singleton object is realized by restricting the instantiation of a class to one object.

HttpContext.Current.Session 是专用于单个用户的区域;存储在会话的任何对象将只用于创建它的用户/会话使用。

HttpContext.Current.Session is an area dedicated to a single user; any object stored in Session will be available only for the user/session that created it.

保存在应用程序的任何对象将只为每个用户/会话使用。

Any object stored in Application will be available only for every user/session.

所有的静态对象同时,将仅适用于每一个用户/会话。 建议实现始终使用静态的对象。为什么你没有?

Any static object also, will be available only for every user/session. Suggested implementations always use static objects.. why didn't you?

这篇关于HttpContext类和它的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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