Events and memory leaks in .NET.

I am using C # .NET 3.5 ... and I was working on decoupling a BLL object by moving database related activities into a separate work object. A work object adds objects to the database, and events indicate a successful or unsuccessful call to the BLL object.

When I instantiate a work object in BLL, I hook up work events and set up a BLL event handler using the syntax event + = delegate (eventhandler).

I heard that unless I explicitly release the listeners with the syntax - =, when the worker is configured to have potential for memory leaks.

All this processing happens in the Windows service, which collects messages from the queue and calls the corresponding BLL object ... I am worried that I can introduce a memory leak into this process.

+4
source share
4 answers

Signing an event adds a link from the subscriber to the provider.

x.Event + = y.handler means that x now contains a reference to y

If x has a longer life than y, then y cannot be garbage collected until all references to x disappear.

In your case, you listen to events from BLL employees (if I understand you correctly), then you have links to workers who remained in BLL, if you do not refuse the explanation.

However, if you finish at the same time as the BLL, it does not matter.

+6
source

What you heard is true. As long as your object subscribes to an event from another available object, the runtime does not release the subscribing object. If your application creates one or a small set of work objects at the beginning during its life cycle, then you should be fine. If the application creates a work object for each BLL object, but the reference to the BLL instance is freed, you should be fine too.

The dangerous thing is to blindly subscribe the instance method to a static event or an object instance event with a long lifetime.

+3
source

If you only sign up for an event once in your service, you should be fine.

+1
source

Explore the use of the .NET desktop or the thread pool and synchronization mechanisms available with these solutions.

0
source

All Articles