I have run into an issue which can be replicated in the following way (you need IIS8 so must be on Windows 8+ or Windows Server 2012 R2+):
Create a new website in IIS Manager, say TestWs on port 8881, pointing to a new folder, say C:\temp\testws, and add the following Web.config file in there
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
<%@ WebHandler Language="C#" Class="WsHandler" %>
using System;
using System.Threading;
using System.Web;
public class WsHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.AcceptWebSocketRequest(async webSocketContext =>
{
while (true)
{
await webSocketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(new byte[1024]), CancellationToken.None);
}
});
}
public bool IsReusable { get { return true; } }
}
var ws = new WebSocket("ws://localhost:8881/wshandler.ashx");
ws.onclose = function() { console.log('closed'); };
ws.close();
As far as I know, while a WebSocket is open, IIS won't tear down the app domain, so you see this behaviour exhibited.
The best I can suggest is that you do some cross process signalling to force the old instance to shutdown. You could achieve this with an EventWaitHandle:
Create a named EventWaitHandle in your web application, and signal it at startup.
On a separate thread, wait on the wait handle
When it is signalled, call HostingEnvironment.InitiateShutdown to force any running old instance to shutdown.