Is it bad practice to subscribe to events in a C # extension method?

In this case, is it a bad idea to subscribe to the CloseCompleted proxy?

public static void Close(this MyWCFServiceClient proxy)
{
            proxy.CloseCompleted += (o, e) =>
            {
                if (e.Error != null)
                    proxy.Abort();
            };

            proxy.CloseAsync();
}

      

when the proxy is no longer referencing any code, will it still be garbage collected, or is the event subscription in the extension method hanging around the proxy link?

+2


source to share


2 answers


I wouldn't say this is bad practice, but in general it should probably be obvious that this is going to happen, i.e. clearly documented in the markup ///

. However, in this case we're talking about the death of the object - so the caller probably doesn't expect much with the object after the method is called. I would also like to make it clear (perhaps the name of the method) that this is asynchronous.



Re garbage collector; events keep the subscriber alive; not a publisher. If it proxy

has the right, it will be collected. The anonymous method does not seem to have access to any captured scope (other than itself proxy

) - so there is nothing interesting to store anyway (other than the delegate instance itself).

+5


source


The proxy has a reference to the anonymous delegate, not the other way around. Therefore, if no one is referring to the proxy, it and the anonymous one will be cleared.



+1


source







All Articles