使用Session线程安全吗? [英] Is working with the Session thread-safe?

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

问题描述

考虑到一个用户同时发出多个请求,我是否必须锁定与该会话一起使用的所有代码?

Consider a user making multiple requests at the same time, do I have to lock all code that works with the Session?

例如,如果我有以下情况,则用户在浏览器的一个选项卡中打开一个页面,然后在第二个页面中注销.

If for example I have the following scenario, where in one tab of his browser the user opens a page and in the second he logs out.

请求1:

if(Session["user"] != null)
    lblName.Text = Session["user"].Name;

请求2:

if(logout)
   Session["user"] = null;

访问Name属性时,请求1是否有可能引发NullPointerException?我是否需要锁定请求1中的代码,以确保在检查null后用户仍然存在?还是ASP.NET会以某种方式自动处理此问题?

Is it possible that Request 1 throws a NullPointerException when accessing the Name property? Do i need to lock the code in Request 1, to make sure user still exists after checking for null? Or does ASP.NET deal with this automatically somehow?

推荐答案

和往常一样,答案取决于您所说的安全性".在ASP .NET中,每个请求都获得对其会话状态的独占访问权.这意味着您不必担心在单个请求范围内同步访问.如果Session ["user"]不为空,则在当前请求的整个持续时间内它将为非空.在您的示例中,请求1绝不会引发空引用异常.

As always, the answer depends on what you mean by "safety." In ASP .NET, each request gets exclusive access to its session state. This means that you don't have to worry about synchronizing access within the scope of a single request. If Session["user"] is non-null, then it will be non-null for the entire duration of the current request. In your example, request 1 will never throw a null reference exception.

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

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