Search code examples
asp.netwebsocketdispose

Proper disposal of WebSocket in a WebSocketContext


In ASP.NET, when the handler you provide to HttpContext.AcceptWebSocketRequest gets a AspNetWebSocketContext, should you dispose the context's WebSocket when you are done with it? Or does the web socket get disposed automatically, perhaps after you call WebSocket.CloseAsync?


Solution

  • You should not dispose the web socket. In fact you cannot. AspNetWebSocket.Dispose always throws a NotSupportedException. The summary and exception sections of the MSDN documentation are incorrect. Fortunately, the remarks section is helpful:

    ASP.NET automatically calls the Dispose method on a AspNetWebSocket object to release any resources that remain after your code has finished executing.