Events and garbage collection
Will objects be collected if they have an event that got a delegate?
Example
void DoSomething()
{
MyObj obj = new MyObj();
obj.JobDone += OnJobDone;
obj.Start()
}
Let's say that MyObj launches a thread, processes some data and then calls OnJobDone. Will "obj" be garbage collected if the reference from obj.JobDone to OnJobDone is not removed (i.e obj.JobDone -= OnJobDone)?
[432 byte] By [
verifier] at [2007-11-20 11:48:30]

# 2 Re: Events and garbage collection
Ok. I gotto remove the delagate to get it collected?
What if I do something like this:
private CommandReply SendAndWait(Command cmd)
{
CommandReply reply = null;
cmd.OnReply += delegate(Command command, CommandReply reply2)
{
reply = reply2;
lock (command)
Monitor.Pulse(command);
};
_socket.SendApi(cmd);
lock (cmd)
Monitor.Wait(cmd, 5000);
return reply;
}
Will cmd get garbage collected?
# 3 Re: Events and garbage collection
GC actually checks periodically for any unused references. In some cases, I found GC doesnt collect for brief time after the variable/object goes out of scope. Theres a method in GC to actually force the collection. That helps.
GC.Collect()
# 4 Re: Events and garbage collection
cmd won't get collected as far as i'm aware because (as far as i know) anonymous delegates get expanded to be normal methods inside your class and so you're in the same situation as the first case.
Also, calling GC.Collect() isn't a good idea unless you're 100% sure you actually need to call it.