Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a Singleton class named CacheState. This class publishes many events. The CacheState has a System.Timers.Timer that loops and triggers all these events.

Then in my asp.net application, I subscribe to these events during Application_Start. The Timer in CacheState is also started during this time:

protected void Application_Start(object sender, EventArgs e)
        {           
                CacheState.Instance.ProductChangedEvent += (objSender, argsE) => ProductService.ReloadProductCache(false);
                CacheState.Instance.PageflexChangedEvent += (objSender, argsE) => ProductService.ResetPageflexCache(false);
                CacheState.Instance.DeliveryChangedEvent += (objSender, argsE) => PricingRuleService.ResetDeliveryMethodsCache(false);
                CacheState.Instance.UIItemChangedEvent += (objSender, argsE) => TemplateService.ResetUIItemsCache(false);
                CacheState.Instance.ProductAttributeChangedEvent += Instance_ProductAttributeChangedEvent;
                CacheState.Instance.Start();

        }

I've read that C# Events can cause memory leaks. So, can anyone tell me if I'm doing this wrong?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

The singleton instance holds a references to all objects that have subscribed to its events. If those objects do not live as long as the singleton instance and they do not unsubscribe from these events then they will remain in memory. This is the only case when you experience a memory leak. Clearly, if the event source gets disposed before your listeners the reference will get cleared and if you properly unregister your listeners there is also no reference remaining.

To solve this problem you can implement the Weak Event Pattern or implement e.g. IDisposable in all objects that listen to singleton events and make sure they get properly disposed in your code!

Of course this does not only hold for singleton objects, but for any object that acts as an event source. A singleton event source however is a particularly dangerous case as it usually lives as long as your application runs and thus lives at least as long as any other object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...