简体   繁体   中英

Why is my Lazy<T> re-initializing every time I call Value?

I have a member of my controller

    private Lazy<MyCache> loadedComponentCache = new Lazy<MyCache>(() =>
    {
        MyCache instance = MyCacheb.Instance;
        instance.LoadStuffAsync().Wait();
        return instance;
    }, LazyThreadSafetyMode.PublicationOnly);

that I'm using to lazy-call a long-running method LoadAsync() that will only need called if a certain API endpoint is hit after the user goes to the page.

    [HttpGet]
    public ActionResult GetStuff()
    {
        var results = from component in loadedComponentCache.Value.All()
                      // ... 
    }

Any idea why it's re-loading every time the API endpoint is hit? My understanding is that an instance of my controller is created only when the user goes to the page and thus this will only be hit once per API call per user visiting the page.

You could make loadedComponentCache static but that's not ideal. If you are using an IoC container you could register it as a singleton. These long lived objects are generally to be avoided though if possible.

If you you truely need this long lived cache then you should probably consider using something like Redis which is designed and optimised for this sort of scenario and can be distributed across multiple nodes. https://redis.io/topics/introduction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM