我正在尝试使用缓存保存一些信息以供以后使用。这就是我分配缓存的方式:
foreach(MibGet Device in DeviceValuesList)
{
if (HttpContext.Current.Cache[DeviceID] == null)
{
HttpContext.Current.Cache[DeviceID] = DeviceValue;
}
}
我可以在调试器中看到此代码可以正常工作,我想要的所有数据均已正确分配。但是,当我尝试像这样(从另一个类方法)从缓存中检索此信息时:
if (NewValue != HttpContext.Current.Cache[DeviceID].ToString())
{
HttpContext.Current.Cache[DeviceID] = NewValue;
}
它引发空引用异常。在调试器中,它显示HttpContext.Current
为空。可能是什么问题,我该如何解决?
答案 0 :(得分:1)
HttpContext.Current
,则 HttpContext
为null。每个请求模型ASP.NET使用一个线程。它创建HttpContext
的实例,并将其与处理请求的线程相关联。但是,如果您通过使用任务或异步编程来显式创建或隐式创建线程,则该线程可能未与HttpContext
我建议您使用其他一些未绑定到System.Runtime.Caching.MemoryCache
的缓存类,例如HttpContext
。
答案 1 :(得分:0)
我假设您的缓存是字典。然后代替
if (get.Value != HttpContext.Current.Cache[get.DeviceID.ToString()].ToString())
您应该写
if (!HttpContext.Current.Cache.ContainsKey(get.DeviceID))
在您的第一个代码段中,您还将Device.Value
放入了缓存,但在第二个代码段中,您将了DeviceID
。我看不出来怎么办。