2

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;
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
garik
  • 5,669
  • 5
  • 30
  • 42
  • 2
    possible duplicate of [How do events cause memory leaks in C# and how do Weak References help mitigate that?](http://stackoverflow.com/questions/3662842/how-do-events-cause-memory-leaks-in-c-and-how-do-weak-references-help-mitigate-t) – Jahan Zinedine Oct 04 '11 at 14:51
  • No (if remoteClient isn't referenced elsewhere) but it seems useless as remoteClient will be GC-ed and your handler will never get called. – Guillaume Oct 04 '11 at 14:53

3 Answers3

2

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. Complex client server

Community
  • 1
  • 1
Nasenbaer
  • 4,810
  • 11
  • 53
  • 86
1

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.

Snowbear
  • 16,924
  • 3
  • 43
  • 67
0

No, unless you are in an infinite loop.

AD.Net
  • 13,352
  • 2
  • 28
  • 47
  • He is in infinite loop, which is likely just pseudo code. Ignoring that. It won't leak by itself. – Lee Louviere Oct 04 '11 at 15:02
  • I think the key here is // subscription without unsubscription, you can ask, there is no need to downgrade the answer without understanding it. Thanks. – AD.Net Oct 04 '11 at 15:40