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?
source to share
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).
source to share