views:

161

answers:

2

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

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 referenced by any code, will it still get garbage collected, or does the event subscription in the extension method hang around holding a reference to proxy?

+5  A: 

I wouldn't say it is bad practice, but in the general case it should probably be obvious that this is going to happen, i.e. clearly documented in the /// markup. However, in this case we are talking about the death of an object - so the caller probably isn't expecting to do much with the object after calling the method. I would also want to make it clear (perhaps in the method name) that this is async.

Re garbage-collection; events keep the subscriber alive; not the publisher. If proxy is eligible, then it will be collected. The anonymous method doesn't seem to access any captured scope (except for proxy itself) - so there is nothing interesting to keep alive anyway (except for the delegate instance itself).

Marc Gravell
And what with proxy.Abort()? Proxy here is a parameter of a method, so it's captured by this lambda, therefore a class that will hold reference to proxy object must be created and allocated (after all, it's just a normal method parameter, being an extension method doesn't change anything). Of course it doesn't change anything when it comes to collection, as it will work the same way.
Ravadre
Oh yes, indeed. You might be able to avoid that by casting the sender, but you're right. And as you say, it won't impact collection anyway.
Marc Gravell
+1  A: 

The proxy has a reference to your anonymous delegate, not vice-versa. Therefore, if no one references the proxy, both it and the anonymous will be cleaned up.

HTH, Kent

Kent Boogaart