Reputation:
In .Net, suppose I instantiate an object that starts an asynchronous process (using Delegate.BeginInvoke on one of its methods), then abandon the object by setting the reference to it to null or allowing it to go out of scope. Will the Garbage Collector attempt to collect the object while the asynchronous process is in progress? If not, what is preventing it from collecting the object?
Upvotes: 5
Views: 188
Reputation: 564851
If you're in completely managed code, it will not collect.
The delegate you are firing is part of the object (from your description). As long as it's running, there is an active reference to the object. As soon as the delegate completes, the object will become a candidate for collection.
However, if you're calling into native code in the delegate, there are some situations where the object can actually be finalized before the native code completes. For details, see this MSDN forum thread.
Upvotes: 12