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.
Request 1:
if(Session["user"] != null)
lblName.Text = Session["user"].Name;
Request 2:
if(logout)
Session["user"] = null;
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?
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.