Memory leak delegates with callbacks

public delegate void SendCallbackType(); public class SenderBase { SenderBase() { mySend = new SendCallbackType(SendData); mySend.BeginInvoke(SendCallback, null); } void SendData() { // process / sending data } void SendCallback(IAsyncResult ar) { **SendCallbackType worker = (SendCallbackType)((AsyncResult)ar).AsyncDelegate; worker.EndInvoke(ar);** //Above code is mandatory ? Working fine without them. mySend.BeginInvoke(SendCallback, null); } // Test Dictionary<SenderBase> SenderCollection = new Dictionary(); SenderCollection.Add(new SenderBase()); SenderCollection.Remove(0); // Add and remove seven times 

Objects (SenderBase) are not garbage collection. They continue to move on to the next generation.

Using RedAnts Memory Profiler,

enter image description here

Any suggestions for cleaning the facility.

Thanks.

+4
source share
1 answer

You keep calling mySend.BeginInvoke (). Therefore, the garbage collector always sees a reference to the mySend object in the threadpool thread stack. And thus, do not collect it. And the code continues to work forever, of course.

The non-excitation of EndInvoke () in this scenario is a bad idea, it leaks resources for 10 minutes for each call to BeginInvoke (). The remote access lifetime, remote connection is the basic plumbing that implements the delegate's BeginInvoke () method.

It's hard to find suggestions for cleaning up the code; it just doesn't make sense to do this. You could also start the stream with while (true) {} loop. It will definitely be more effective.

+5
source

All Articles