4

Although HTTP is a stateless protocol, there's this PushStreamContent class that facilitates server-sent events, as you can read here. A Web API implementation may store client streams and periodically send push updates. However, it's a bit of a problem to detect when the client disconnects.

In this discussion, Henrik Nielsen states that:

Detecting that the TCP connection has been reset is something that the Host (ASP, WCF, etc.) monitors but in .NET 4 neither ASP nor WCF tells us (the Web API layer) about it. This means that the only reliable manner to detect a broken connection is to actually write data to it. This is why we have the try/catch around the write operation in the sample. That is, responses will get cleaned up when they fail and not before.

In .NET 4.5 there is a mechanism for detecting client disconnect but I haven't tried it out.

Fast forward two and a half years to today. Does anyone have any idea what this mechanism is, and whether it works?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188

1 Answers1

4

An interesting response was post on this link : link to the article

this is a part of the answer

In .NET 4.5 there is a mechanism for detecting client disconnect but I haven't tried it out.

This (simplified) code works for me:

public HttpResponseMessage Get(HttpRequestMessage request)

{

// Register for client disconnect notifications

object clientId = ...; // this is the object passed to the callback

System.Web.HttpContext.Current.Response.ClientDisconnectedToken.Register(

delegate (object obj)

{

// Client has cleanly disconnected

// obj is the clientId passed in to the register

// handle client disconnection

//...

}

, clientId );

// Normal code from the sample continues

response.Content = new PushStreamContent(...);

}

The ClientDisconnect callback is called back if e.g. you close the client browser page cleanly, but if you pull the network cable out, it does not get notified. So for this unclean disconnection, we still need some other way of detecting this, such as monitoring failures during the timer callback.

Diane Delallée
  • 123
  • 2
  • 9