views:

118

answers:

1

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?

+12  A: 

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.

Reed Copsey
Great, makes total sense. I need to expand a bit on this now though. I've passed an AsyncCallback to the BeginInvoke so that I can do some finalization processing and call EndInvoke when the asynchronous process is complete. Is it true that the delegate call is not complete until after this AsyncCallback is complete? And thus the object will not become a candidate for collection until after the AsyncCallback ends?
Ken
Yes. See http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.asyncresult_members.aspx - there is a handle to your delegate, and hence your object, in the AsyncDelegate property. Until your callback ends, this will not be a candidate for GC.
Reed Copsey
Perfect, much appreciated.
Ken