Reputation: 2767
There are already a couple of questions similar to this one: this and this
In particular I quote Marc Gravell's answer (here):
If you have A publishing an event, and B subscribing to an event (the handler), then it is only a problem not to unsubscribe if A is going to live a lot longer than B.
But I could not find any mention to the special case when the event source and the handler are the same reference, for example:
class Foo
{
public event Action SomeEvent;
public Foo() => SomeEvent += OnSomeEventHappened; //should I unsubscribe somewhere?
private void OnSomeEventHappened(){}
}
I just want to be sure there is no hidden issue with the above code. As far as I know I may never unsubscribe from that event since both the subscriber and the publisher are exactly the same instance.
Would not subscribing prevent my Foo instance from being garbage collected?
Upvotes: 1
Views: 117
Reputation: 4826
This doesn't appear to be necessary.
Based off your comment it sounds like you're most worried about garbage collection (or possible lack of).
I just wrote up a super quick test app inspired by this answer in order to test whether the object was garbage collected. It appears to have been.
Here is the code I used to test (running in Release), using the same code you have for your Foo
class (left out for simplicity):
class Program
{
[STAThread]
static void Main()
{
Foo foo = new Foo();
WeakReference fooRef = new WeakReference(foo);
Console.WriteLine(fooRef.IsAlive); //Displays "True"
foo = null;
GC.Collect();
Console.WriteLine(fooRef.IsAlive); //Displays "False"
Console.ReadKey();
}
}
Output:
True
False
Here's a fiddle that seems to do the job as well (assuming it doesn't have its own garbage collection quirks... I'm not a super experienced "fiddler").
Upvotes: 2