Andronicus
Andronicus

Reputation: 1879

Is it bad practice to subscribe to events in a C# Extension Method?

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?

Upvotes: 2

Views: 474

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178650

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062660

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).

Upvotes: 5

Related Questions