Does this event-handling code cause a memory leak?
Is this a memory leak?
private void Process()
{
for (; ; )
{
// local variable
RemoteClient remoteClient = new RemoteClient(..);
// subscription开发者_如何转开发 without unsubscription
remoteClient.BadClient += new EventHandler(remoteClient_BadClient);
}
..
}
public class RemoteClient
{
...
public event EventHandler BadClient;
}
It depends on what else is in the RemoteClient class. If there is NO object to dispose
this is no memory leak. If there are any objects with IDisposable
content, you need to inherit ÌDisposable` and destroy those objects.
Also its not new to you to remove the handler and exit loop I think.
Because client sounds like an webservice it could be important to have a look to called asynchron Threads. .NET: Do I need to keep a reference to WebClient while downloading asynchronously?
Also if the whole stuff becomes to be more complex, it is important to check the objects state.
This is not a memory leak in case if you will exit your for
loop. Each remoteClient
will hold reference to a remoteClient_BadClient
delegate but remoteClient
itself will be applicable for garbage collection after each iteration (if you do not store reference to remoteClient
somewhere else!). Collecting remoteClient
will also dispose the reference to remoteClient_BadClient
delegate which will allow collecting it also.
No, unless you are in an infinite loop.
精彩评论