Question:
Consider the following code:
<code class="language-c#">MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass = null;</code>
Will pClass be garbage collected? Or will it persist and continue to trigger events? Do you need to unsubscribe from events like this:
<code class="language-c#">MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass.MyEvent -= MyFunction; pClass = null;</code>
Answer:
Garbage collection by event publisher:
Subscription to MyEvent does not affect the garbage collection of pClass (publisher).
Garbage collection of target object:
Generally, garbage collection behavior depends on whether MyFunction is an instance method or a static method:
Other notes:
The above is the detailed content of Will Event Handlers Prevent Garbage Collection of My Objects?. For more information, please follow other related articles on the PHP Chinese website!