0

Unless I've fundamentally misunderstood the way events and garbage collection work in C#, if an object has subscribed to an event, the event can still be raised on that object, and the event handler executed, even if the object is out of scope and eligible for garbage collection.

So my question is this - is there any way for an object's event handler to check whether the object itself is eligible for garbage collection, with a view to ignoring and/or unsubscribing from the event?

Dave
  • 3,429
  • 2
  • 26
  • 29
  • 1
    A better question would be, "if an event handler is running and therefore has a reference to its own object, could it possibly be eligible for garbage collection?" And the answer is "No." – madreflection May 28 '21 at 17:04
  • 1
    Related: https://stackoverflow.com/a/4526840 – madreflection May 28 '21 at 17:06
  • 2
    No, it is not "out of scope". The delegate object underlying the event has a reference, it doesn't disappear until the event is unsubscribed. – Hans Passant May 28 '21 at 17:06
  • 1
    _"even if the object is out of scope and eligible for garbage collection"_ -- the underlying premise of your question is just plain wrong. If the object is still subscribed to an event of an object that itself is not eligible for garbage collection, then the object with the object handler is **not** _"...out of scope and eligible for garbage collection..."_. Note that GC depends on whether an object is _reachable_, not on its "scope". See duplicate for details about how event handlers prevent GC from occurring. – Peter Duniho May 28 '21 at 17:15
  • 1
    In other words, no it's not possible to test for the condition you describe, because that condition is a completely made up, imaginary, impossible condition that actually never happens. – Peter Duniho May 28 '21 at 17:16
  • Maybe you search for WeakReference or Weak Event Pattern? – Alexander Petrov May 28 '21 at 17:27

0 Answers0