Fully clearing a dictionary of multicast delegates

268 views Asked by At

I have a Dictionary of multicast delegates where the key is a particular message type and the values are multicast delegates i.e. message handlers.

When I want to clear down that Dictionary I want to ensure that all delegates are unbound and dereferenced and ultimately garbage collected - is it sufficient to clear down the dictionary or should I enumerate the values (multicast delegates) and set them to null first before clearing down the dictionary?

3

There are 3 answers

1
Emily On

Just set them to null.

foreach (var d in dict)
{
    d = null;
}

And when the compiler no longer has any references to these it's gonna garbace collect it for you.

Ultimately, just make the whole dict to null:

dict = null;

Garbage collection in C# should not be an issue.

0
Marc L. On

Unless you have a counter example (in which case you should open a bug report with MS) garbage collection in .NET should not be a concern. It's fairly sophisticated, and can track down objects that aren't referenced in code, even if they are part of an arbitrarily large object graph that is un-referenced from the running image.

Even so, there isn't a difference between clearing the dictionary and setting all its values to null. Both have the same effect of simply dereferencing the underlying values. This is overkill.

The real concern with .NET isn't reference-safety, but resource leaking: any IDisposable class should be disposed before dereferencing it. However, MulticastDelegate is not a disposable class, so this is moot.

In other words: this is .NET, not C. Stress less. No worries.

0
Sprotty On

The System.Delegate (and System.MulticastDelegate) classes are handled in just the same way as any other classes, they are just happen to contain pointers to a function and target object. So to all intents and purposes you can just treat it as a reference to the target object.

If you are done with them just Clear the dictionary, if your done with the containing object you don't really need to even do that. Setting them to null individually will do nothing that clearing the dictionary wont do.

Once any object is no longer reachable it is eligible for garbage collection, if your not familiar with the garbage collection mechanism then I strongly recommend you read around the subject a bit.