我有一个对象可以处理我的数据访问层 (DAL) 的内存缓存,我需要在线程之间保留它。根据我的阅读,首选方法是使用 httpcontext.item 和如下代码:
Shared Property DALList() As Dictionary(Of String, DAL)
Get
If Not Web.HttpContext.Current.Items.Contains("_DALList") Then
Web.HttpContext.Current.Items.Add("_DALList", New Dictionary(Of String, DAL))
End If
Return Web.HttpContext.Current.Items("_DALList")
End Get
Set(ByVal value As Dictionary(Of String, DAL))
If Not Web.HttpContext.Current.Items.Contains("_DALList") Then
Web.HttpContext.Current.Items.Add("_DALList", value)
Else
Web.HttpContext.Current.Items("_DALList") = value
End If
End Set
End Property
两个问题:这是否试图序列化对象,如果是,我如何让它保持对象完好无损并在内存中引用它而不是序列化它?我需要保持对象完好无损,因为它在后台处理数据库连接和缓存。
[编辑]
当我运行它时,我收到一个导致页面挂起的错误。事件日志中有两个项目。
错误应用程序 w3wp.exe,版本 7.0.6001.18000,时间戳 0x47919ed8,错误模块 kernel32.dll,版本 6.0.6001.18000,时间戳 0x4791ada5,异常代码 0xe053534f,错误偏移量 0x000000000002649d,进程 id 0x%10 0x%9,应用程序启动时间.
和
状态服务器已关闭过期的 TCP/IP 连接。客户端的 IP 地址是 127.0.0.1。过期的读取操作开始于 04/07/2009 20:44:29。
然后,我重新散列代码以将项目放入字典对象中,并根据会话 ID 得到这些 smae 错误。如果我使用静态变量,它可以正常工作,但是我遇到了我原来的问题,即用户将访问其他用户数据(显然这不是一个选项)。
重新散列的版本如下:(这适用于第一种方法,但不适用于此方法)
Shared _CurrentScope As New Dictionary(Of String, DALScope)
Public Shared Property CurrentScope() As DALScope
Get
If Not _CurrentScope.ContainsKey(Web.HttpContext.Current.Session.SessionID & "_CurrentScope") Then
_CurrentScope.Add(Web.HttpContext.Current.Session.SessionID & "_CurrentScope", New DALScope)
End If
Return _CurrentScope(Web.HttpContext.Current.Session.SessionID & "_CurrentScope")
End Get
Set(ByVal value As DALScope)
If Not _CurrentScope.ContainsKey(Web.HttpContext.Current.Session.SessionID & "_Currentscope") Then
_CurrentScope.Add(Web.HttpContext.Current.Session.SessionID & "_Currentscope", value)
Else
_CurrentScope(Web.HttpContext.Current.Session.SessionID & "_Currentscope") = value
End If
End Set
End Property
[编辑]
在同一会话下有多个 web 请求的情况下,锁定的好处。我最终使用了 httpcontext.item 方法,发现我的问题与属性是 byval 而不是 byref 有关。我已经更改了我的代码以包含通过 ref 处理 hte 对象的方法,现在它可以工作了。