恕我直言,很难理解您的问题,但我会尝试。
据我了解,您正在执行以下操作:
string helloWorld = string.Empty;
if (this.Session["myObject"] == null)
{
// The object was removed from the session or the session expired.
helloWorld = this.CreateNewMyObject();
}
else
{
// Session still exists.
helloWorld = this.Session["myObject"].ToString(); // <- What if the session expired just now?
}
或者
// What if the session existed here...
if (this.Session["myObject"] == null)
{
this.Session["myObject"] = this.CreateNewMyObject();
}
// ... but expired just there?
string helloWorld = this.Session["myObject"].ToString();
我认为该Session
对象由与页面请求相同的线程管理,这意味着检查对象是否存在是安全的,而不是在没有 try/catch 的情况下使用它。
我错了:
对于缓存对象,您必须意识到您实际上是在处理跨多个线程访问的对象
来源:ASP.NET 缓存和会话状态存储
我没有仔细阅读 Robert Koritnik 的答案也是错误的,事实上,它清楚地回答了这个问题。
事实上,您会被警告在页面请求期间可能会删除对象。但是由于Session
生命周期依赖于页面请求,这意味着只有当您的请求花费的时间超过会话超时时,您才必须考虑删除会话变量(请参阅 Robert Koritnik 的答案中的会话如何处理)。
当然,这种情况非常少见。但是,如果在您的情况下,您非常确定页面请求可能需要超过 20 分钟(默认会话超时),那么您必须考虑到在检查对象是否存在后可能会删除它,但是在你真正使用它之前。
在这种情况下,您显然可以增加会话超时,或者在访问会话对象时使用 try/catch。但是恕我直言,如果页面请求需要几十分钟,您必须考虑其他替代方案,如 Windows 服务来完成这项工作。