You need to enable JavaScript to run this app. ASP.Net VB开发中Public Shared变量的优化替代方案问询
优惠活动
大模型
产品
解决方案
定价
更多

ASP.Net VB开发中Public Shared变量的优化替代方案问询

问题根源

Public Shared 变量的作用域是整个应用程序域,站点所有访问用户共享同一份内存存储,多用户并发操作时必然出现数据覆盖、串扰问题,这是你遇到问题的核心原因。而WebForm页面对应类的Public Shared变量同样属于应用域级别,和API类的共享变量没有本质区别,你遇到的回发数值丢失是混淆了声明方式:只有非Shared的页面成员才会在请求结束、页面对象销毁后丢失,Shared成员不会丢失但依然存在多用户串扰问题。

解决方案

你完全可以封装一个按用户/会话隔离、支持自定义过期时间的变量存储类,基于ASP.NET原生内置的能力即可实现,不需要引入额外组件。

两种可选实现路径

方案1:基于Session封装(适合全局统一过期的场景)

Session是ASP.NET原生的用户级隔离存储,天然实现不同用户的数据拆分,默认支持全局统一配置过期时间,实现成本最低。

封装代码示例

Imports System.Web
Imports System.Web.SessionState

Public Class UserSessionStorage
    ' 存储数据,expireMinutes不传则使用Web.config配置的全局Session过期时间
    Public Shared Sub SetValue(Of T)(key As String, value As T, Optional expireMinutes As Integer = 0)
        Dim session As HttpSessionState = HttpContext.Current.Session
        If session Is Nothing Then Return
        
        session(key) = value
        If expireMinutes > 0 Then
            session.Timeout = expireMinutes
        End If
    End Sub

    ' 读取数据
    Public Shared Function GetValue(Of T)(key As String, Optional defaultValue As T = Nothing) As T
        Dim session As HttpSessionState = HttpContext.Current.Session
        If session Is Nothing OrElse session(key) Is Nothing Then
            Return defaultValue
        End If
        Return CType(session(key), T)
    End Function

    ' 手动删除指定存储项
    Public Shared Sub RemoveValue(key As String)
        Dim session As HttpSessionState = HttpContext.Current.Session
        If session IsNot Nothing Then
            session.Remove(key)
        End If
    End Sub
End Class

方案2:基于Cache封装(适合单个存储项独立设过期的场景)

如果需要给不同变量设置不同的过期时间,不受全局Session配置限制,可以用Cache存储,键名拼接用户SessionID实现用户隔离,支持单独给每个存储项设置绝对过期或者滑动过期规则。

封装代码示例

Imports System.Web
Imports System.Web.Caching

Public Class UserPerItemStorage
    ' 存储数据,expireMinutes为当前存储项的独立过期时间(单位:分钟)
    Public Shared Sub SetValue(Of T)(key As String, value As T, expireMinutes As Integer)
        Dim context As HttpContext = HttpContext.Current
        If context Is Nothing Then Return
        ' 拼接用户SessionID作为键前缀,保证不同用户的数据隔离
        Dim userUniqueKey = $"{context.Session.SessionID}_{key}"
        ' 示例为绝对过期,需要滑动过期可替换为DateTime.MaxValue+TimeSpan.FromMinutes(expireMinutes)
        context.Cache.Insert(userUniqueKey, value, Nothing, 
            DateTime.Now.AddMinutes(expireMinutes), Cache.NoSlidingExpiration)
    End Sub

    ' 读取数据
    Public Shared Function GetValue(Of T)(key As String, Optional defaultValue As T = Nothing) As T
        Dim context As HttpContext = HttpContext.Current
        If context Is Nothing Then Return defaultValue
        Dim userUniqueKey = $"{context.Session.SessionID}_{key}"
        Dim cacheVal = context.Cache(userUniqueKey)
        If cacheVal Is Nothing Then Return defaultValue
        Return CType(cacheVal, T)
    End Function

    ' 手动删除指定存储项
    Public Shared Sub RemoveValue(key As String)
        Dim context As HttpContext = HttpContext.Current
        If context Is Nothing Then Return
        Dim userUniqueKey = $"{context.Session.SessionID}_{key}"
        context.Cache.Remove(userUniqueKey)
    End Sub
End Class

使用方式

替换你之前API类中Public Shared变量的读写逻辑即可:

  • 存储搜索结果:UserPerItemStorage.SetValue("UserSearchResult", 你的搜索结果对象, 20) ' 20分钟后过期
  • 读取搜索结果:Dim result = UserPerItemStorage.GetValue(Of List(Of 搜索结果实体类型))("UserSearchResult")

注意事项

  • 多服务器负载均衡部署场景下,Session需要配置为StateServer或者SQLServer存储模式,避免不同服务器之间Session不互通的问题
  • 不要在上述存储中存放过大的对象,避免占用过多服务器内存,大数据量建议做持久化存储后只存查询标识
  • 仅全局公共数据才需要使用Application或者共享变量存储,所有用户专属数据都使用上述两种隔离方案即可完全避免串扰问题

内容的提问来源于stack exchange,提问作者user2312463

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 20:06:00