HttpContext.Current.Session 和 HttpContext.Current.Items 有什么区别?

What's the difference between HttpContext.Current.Session and HttpContext.Current.Items?

我知道 Session 中存储的数据在用户关闭浏览器之前一直有效,而 Items 中存储的数据在处理 request/response 之前一直有效。

我也知道如果我调用 Session.Abandon() 它将使 Session 表现得像 Items。

我做了一些测试,在第一种情况下,我在 Session 中放置了 Entity Framework DbContext(以保持与 sql 服务器的连接),在 Items 中,所以如果它不存在我实例化它否则我从这些存储之一获取它。

我看到从 Session 查询上下文比从 Items 查询上下文更快。

这很奇怪,因为我在两种情况下都从上下文中检查了 Dispose() 方法,并且它按预期被调用 - 在 Session 或 Items 结束时。

现在,如果我调用 Session.Abandon(),那么就执行速度而言,两种情况下的查询是相同的。

这是怎么回事,为什么我会遇到这种情况?

由于上下文已经存在,并且查询已经执行,它可能被缓存,这反过来会缩短执行时间。

您应该了解冷查询与热查询,以及它们对您的应用程序有何影响。

Cold vs warm queries

The very first time any query is made against a given model, the Entity Framework does a lot of work behind the scenes to load and validate the model. We frequently refer to this first query as a "cold" query. Further queries against an already loaded model are known as "warm" queries, and are much faster.