Automatically refresh ASP.NET Output Cache on expi

2020-03-25 06:15发布

问题:

I have a few expensive pages that I cache using ASP.NET output cache like so,

[OutputCache(Duration=3600, VaryByParam = "none")]

Obviously, the cache will expire after 3600 seconds (1 hour), and the next poor guy that happens to load that page will have to wait for the cache to be refreshed from the dabatase.

My question is, how do I make the cache to be refreshed immediately on expiry? So that the next guy who happens to visit the page when the cache had just expired will not have to wait for the cache to be refreshed and instead is served with a new cache?

Update: I need the cache to be updated pretty frequently (1 hour to 3 hour) as I do not want the data to stale for too long either.

回答1:

I don's think, that you can achieve what you need using just OutputCache.

Basically you need data storage and worker. For storage you can using anything from static variable to external database.

Same thing with worker. It's might be just simple long running task or external service. Basic sample, so you can get the idea of what i am talking about

public class TestController : Controller
{
    private static int _result = 0;


    static TestController()
    {
        Task.Factory.StartNew(async () =>
        {
            while (true)
            {
                await Task.Delay(new TimeSpan(0, 0, 5));
                _result++;
            }

        }, TaskCreationOptions.LongRunning);
    }

    public ActionResult Index()
    {
        return Json(_result, JsonRequestBehavior.AllowGet);
    }
}