Taking Action on Client Close

How do I clean up resources on the server when a duplex client closes its half of the connection?

Duplex services sometimes need to be a little bit more aggressive cleaning up after clients. Unlike with other channel shapes, a duplex client can decide to stop sending requests but continue to receive responses from the server. When that happens, the polite thing for the client to do is to close its half of the connection so that the server knows that no more requests are coming.

The server has to do some extra work to handle this half close case. Since a half close doesn't permit the server to dispose of the channel or the instance yet, cleanup may need to be split into multiple parts so that the request infrastructure can be torn down sooner. The server also needs some way to detect that a half close is taking place. You can't rely on the client sending a terminating message because the client might time out or decide not to send the message. The server should try to avoid letting client problems tie up resources unnecessarily.

The IInputSessionShutdown extensibility point allows a service to run code on client disconnection regardless of whether the disconnection was graceful or unexpected. You can insert your code by writing a behavior that adds to the InputSessionShutdownHandlers collection of the DispatchRuntime. There are two methods that will get call backs depending on whether a particular disconnection was graceful or unexpected.

 public interface IInputSessionShutdown
{
   void ChannelFaulted(IDuplexContextChannel channel);
   void DoneReceiving(IDuplexContextChannel channel);
}

In the case of unexpected disconnections it may take some time for the server to realize that the client has disconnected. However, this is better than always having to wait for the full idle timeout to expire.

Next time: Basing Authorization on the Message Body