问题描述
销毁会话和删除其值有什么区别?你能提供一个例子来证明这一点吗?
我搜索了这个问题,但没有掌握完整的答案.一些答案是:
Session.Abandon()
销毁会话Session.Clear()
只是删除所有值
一位朋友告诉我:
清除会话不会取消设置会话,它仍然存在用户的相同 ID,但具有值简单地清除.
放弃会破坏会话完全,这意味着你需要在你可以之前开始一个新的会话在会话中存储更多值对于该用户.
下面的代码有效并且不会抛出任何异常.
Session.Abandon();会话["tempKey1"] = "tempValue1";
当你放弃()一个会话时,你(或而用户)将获得一个新的会话 ID
当我测试 Session 时,它不会在我放弃会话时进行任何更改.
我只发现一个区别:session.Abandon()
引发 Session_End
事件
Clear - 从会话状态集合中删除所有键和值.
Abandon - 删除会话中存储的所有对象.如果不显式调用 Abandon 方法,服务器会在会话超时时删除这些对象并销毁会话.
它还引发诸如 Session_End 之类的事件.
Session.Clear 可以比作从书架上取走所有书籍,而 Session.Abandon 更像是扔掉整个书架.
你说:
当我测试 Session 时,它不会在我放弃会话时进行任何更改.
这在您仅在一个请求内时是正确的.
在下一个请求中,会话将有所不同.但是 会话 ID 可以重复使用,以便 ID 保持不变.
如果您使用 Session.Clear,您将在许多请求中使用相同的会话.
一般来说,大多数情况下需要使用Session.Clear.
如果您确定用户会离开您的网站,则可以使用 Session.Abandon.
回到差异:
- 放弃会引发 Session_End 请求.
- Clear 会立即删除项目,Abandon 不会.
- Abandon 释放 SessionState 对象及其项目,以便它可以通过垃圾回收来释放资源.Clear 保持 SessionState 和与之关联的资源.
What is the difference between destroying a session and removing its values? Can you please provide an example demonstrating this?
I searched for this question, but don't grasp total answer. Some answers are:
Session.Abandon()
destroys the sessionSession.Clear()
just removes all values
A friend told me this:
The below code works and doesn't throw any exceptions.
Session.Abandon();
Session["tempKey1"] = "tempValue1";
When I test Session, it doesn't makes any change when I Abandon the session.
I just find one difference:session.Abandon()
raises Session_End
event
Clear - Removes all keys and values from the session-state collection.
Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out.
It also raises events like Session_End.
Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.
You say:
This is correct while you are doing it within one request only.
On the next request the session will be different. But the session ID can be reused so that the id will remain the same.
If you will use Session.Clear you will have the same session in many requests.
Generally, in most cases you need to use Session.Clear.
You can use Session.Abandon if you are sure the user is going to leave your site.
So back to the differences:
- Abandon raises Session_End request.
- Clear removes items immidiately, Abandon does not.
- Abandon releases the SessionState object and its items so it can ba garbage collected to free the resources. Clear keeps SessionState and resources associated with it.
这篇关于Session.Abandon() 和 Session.Clear() 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!