1

Possible Duplicate:
Weak references

I understand the concept of a weak reference, but I am unable to find where I should use a weak reference in C#.

Community
  • 1
  • 1
sushil pandey
  • 752
  • 10
  • 9
  • To keep track of when an objects is garbage collected. As for when you'd want to do that, maybe for in-application profiling or something. – George Duckett Jan 04 '12 at 16:38
  • In general, if you don't know when to use a `WeakReference` you should probably avoid it. It's a way for you to hold onto a reference to an object, but not prevent it from being collected if you are the last remaining reference and it needs the space. – James Michael Hare Jan 04 '12 at 16:39
  • See [Weak References (MSDN)](http://msdn.microsoft.com/en-us/library/ms404247.aspx) for an example of their use beyond tracking GCs. – George Duckett Jan 04 '12 at 16:44

1 Answers1

4

A good example of where to use a WeakReference would be when implementing the EventAggregator pattern.

Say you have the code

eventAggregator.Subscribe<AnEventType>(this.DoSomethingDelegate);

then you will specifically ahve to unsubscribe later if you don't want to have a potential memory leak. See Explicitly Removing Event Handlers for more info.

If however the internals of the EventAggregator hold on to the DoSomethingDelegate using a weak reference, then no unsubscription is necessary.

For further learning, I suggest taking a look at the implementation of EventAggregator in the Microsoft Practices library using ILSpy. This internally uses a WeakReferenceDelegate type which wraps a Weakdelegate and allows subscription without explicit unsubscription and no chance of a memory leak.

Best regards,

Community
  • 1
  • 1
Dr. Andrew Burnett-Thompson
  • 20,980
  • 8
  • 88
  • 178