以下是我将如何使用 ASP.NET 页面中的以下伪代码来解决您的问题。您要将结果缓存在内存中,并在数据在缓存中超过 10 分钟时刷新数据。
var data = Cache["data"];
if (data.Timestamp <=
DateTime.Now.Substract(TimeSpan.FromMinutes(10)))
{
//Refresh cache with new data when it's older than 10min.
// You could hypothetically do this in a separate thread
// if you wanted to do so.
data = new Data(GetFromDb(), timestamp);
Cache["data"] = data;
return Cache["data"];
}
else
{
//Use existing data
return Cache["data"];
}
这是关于如何使用 IIS 的运行时缓存的参考。
如果您想确保您的缓存值始终是新鲜的,您可以创建一个每 10 分钟访问一次此页面的作业,而不是您当前解决方案的方法。
还有很多其他方法可以用来缓存数据,但使用 OS 文件系统并不是真正的最佳方法。