Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# - Subscribing to events published by a Singleton Class

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...