需要澄清 Session 的实际工作原理吗?
在很多地方我都看到过以下模式。考虑代码:
Customer cust = (Customer) Session["Customer"];
//Do something to the object cust
Session["Customer"] = cust
和代码:
Customer cust = (Customer) Cache["Customer"];
//do something to object cust
Cache["Customer"] = cust;
现在,在第二种情况下,不需要将 cust 对象放回缓存,因为引用是相同的,并且对 cust 对象的任何更改都应反映在缓存中。
但我认为 Session 的情况并非如此,其中 cust 对象必须显式放回 Session 中。不过,我不确定。如果我没有按上述方式明确指定更改,那么更改会反映在会话中吗?
如果需要显式完成,为什么与 Cache 对象的行为有所不同?这两个地方我们似乎都在进行引用传递。
这适用于 C#、ASP.NET
At a lot of places I have seen the following pattern. Consider the code:
Customer cust = (Customer) Session["Customer"];
//Do something to the object cust
Session["Customer"] = cust
and the code :
Customer cust = (Customer) Cache["Customer"];
//do something to object cust
Cache["Customer"] = cust;
Now, in the second case, putting the cust object back to Cache is not required as the reference is the same and any changes to the cust object shall be reflected in the cache.
But I dont think that is the case in case of Session, where the cust object has to be explicitly put back into the Session. However, I am not sure. Will the change reflect in Session if I do not explicitly specify the change as above?
And if it needs to be done explicitly, why the difference in behavior with Cache object? Both places we seem to be doing a reference passing.
This is for C#, ASP.NET
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符串是不可变的。为什么要担心数据类型以及是否需要重新分配它?只需重新分配它即可安全且清楚地了解您的意图。
要明白我的意思,请运行它并检查值。您会看到它在会话中没有改变。 x 的值为“bar”。
Strings are immutable. Why worry about a data type and whether or not you need to reassign it? Just reassign it to be safe and clear about your intentions.
To see what I mean, run this and check the values. You will see it did NOT change in the session. The value of x will be "bar".
您不必显式地将对象重新分配回会话。对从 Session 检索的对象所做的任何更改都将反映并保留在 Session 中。缓存不同,因为它可能会过期。如果您需要任何进一步的帮助,请告诉我。
另一件事是,InProc Session 比 Cache 更快,因为 Cache 在返回对象之前必须检查过期时间。
存储在 Session 和 Cache 中的对象只是指向该对象的指针,因此对对象所做的任何更改都将被持久化,而无需显式地将对象重新分配回它来自的 Session 或 Cache。
You do not have to explicitly reassign the object back to the Session. Any changes made on an object retrieved from Session will be reflected and persisted within the Session. Cache is different because it may expire. If you need any further assistance, let me know.
One other thing, InProc Session is faster than Cache because Cache has to check expirations before returning the object.
The object stored in Session and in Cache is just a pointer to the object, so any changes made to the object will be persisted WITHOUT the need to explicitly reassign the object back to the Session or Cache it came from.