We are using a pub-sub model in our WCF application that pretty much follows the Microsoft sample: Design Patterns: List-Based Publish-Subscribe.
Whilst the service provides a notion of subscribe()
and unsubscribe()
, what is the best practice to handle the cleanup in the situation when a client dies or the channel faults? Currently, when a client subscribes I attach to handlers to the current InstanceContext
's Closed
and Faulted
events (the service users an PerSession instance context mode and netTcpBinding):
_communicationObject = OperationContext.Current.InstanceContext;
_communicationObject.Closed += OnClientLost;
_communicationObject.Faulted += OnClientLost;
The OnClientLost
handler simply unsubscribes the client, however:
This question poses a similar question but ultimately does not provide answers to the cases outside of the client calling subscribe and/or unsubscribe
Thanks
I did some testing where I attached handlers to the Closed and Faulted events of the callback channel, then killed the client at the point just before the callback would be invoked by the server. On each trial, the Closed/Faulted event was fired instantaneously and before the server attempted to invoke the callback. All the same, I still have the callback invocation wrapped in a try-catch block because the destruction of the client channel could occur just as another thread was entering the callback.
The only clean-up necessary was to remove the reference to the callback channel. WCF and the garbage-collector do the rest.
Handling those events will keep your list of subscribers synchronized. It is indeed robust enough. Just remember that if a client drops during a transmission of a message, you might get an exception before those events fire, so be ready to ignore them so that the events can clean up.
Except for removing the client from he subscribers list, additional cleanup depends entirely on your application (i.e. freeing resources you acquired when the client connected). I am not aware of any other cleanup that is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With