C# 从其他线程访问HttpRuntime.Cache

C# 从其他线程访问HttpRuntime.Cache,c#,caching,httpruntime.cache,httpruntime,C#,Caching,Httpruntime.cache,Httpruntime,我的ASP.Net后面有一个线程。在这个线程中,我将数据放入缓存,如下所示: HttpRuntime.Cache.Insert("test", "test", null, DateTime.Today.AddHours(6), Cache.NoSlidingExpiration); if (HttpRuntime.Cache.Count > 0) { var test = (string)HttpRuntime.Cache["test"]; } 在另一个线

我的ASP.Net后面有一个线程。在这个线程中,我将数据放入缓存,如下所示:

HttpRuntime.Cache.Insert("test", "test", null, DateTime.Today.AddHours(6), Cache.NoSlidingExpiration);   
 if (HttpRuntime.Cache.Count > 0) {
          var test = (string)HttpRuntime.Cache["test"];
 }
在另一个线程(网页)上,我首先检查缓存是否包含任何数据,然后尝试从缓存中获取对象,如下所示:

HttpRuntime.Cache.Insert("test", "test", null, DateTime.Today.AddHours(6), Cache.NoSlidingExpiration);   
 if (HttpRuntime.Cache.Count > 0) {
          var test = (string)HttpRuntime.Cache["test"];
 }

编辑:每次我尝试执行
var test=(string)HttpRuntime.Cache[“test”]缓存将变空(或删除对象,未测试缓存中的多个对象),加上
var test
也为空。这当然是在HttpRuntime.Cache.Count大于0时发生的


哦,它没有给出任何异常或任何东西

在您的代码中有一个潜在的不一致,即DateTime.Today.AddHours(6),它将不起作用。您应该使用DateTime.Now.AddHours(6)


DateTime。今天是从
12:00 AM
开始的当前日期,如果代码在
6:00 AM
之后运行,则httpruntime缓存显然不可用。

在.NET中的缓存对象是线程安全的,因此不必按线程获取数据。您可以查看以下文章:


调整你的持续时间:
DateTime.Now.AddHours(6)

你能澄清一下“在这一行之后”吗?你是说在你的if语句
Cache.Count>0
中,但是在
var test=(string)HttpRuntime.Cache[“test”期间的某个时间它是空的?每次当我尝试执行
var test=(string)HttpRuntime.Cache[“test”]缓存将变为空(或者将删除对象,尚未测试该对象),加上
var test
也为空。这当然是在
HttpRuntime.Cache.Count
大于0时发生的