Asp net core websocket manager websockets are always disposed


ASP.NET is a popular programming language used for building web applications. One of the challenges developers face is managing websockets in ASP.NET Core. In this article, we will explore how to solve the issue of disposing websockets in ASP.NET Core WebSocket Manager.

Understanding the

When working with websockets in ASP.NET Core, it is important to manage the lifecycle of the websocket connections. If websockets are not disposed of correctly, it can lead to memory leaks and other performance issues.


To solve the problem of disposing websockets in ASP.NET Core WebSocket Manager, we can follow :

Step 1: Create a WebSocket Manager

First, we need to create a WebSocket Manager class that will handle the management of websockets. This class will be responsible for creating, storing, and disposing of websocket connections.

public class WebSocketManager
     readonly ConcurrentDictionary _websockets;

    public WebSocketManager()
        _websockets = new ConcurrentDictionary();

    public void AddWebSocket(string id, WebSocket websocket)
        _websockets.TryAdd(id, websocket);

    public void RemoveWebSocket(string id)
        _websockets.TryRemove(id, out _);

    public  Task DisposeWebSockets()
        foreach (var websocket in _websockets.Values)
            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "WebSocket manager disposed", CancellationToken.None);

Step 2: Register WebSocket Manager

Next, we need to register the WebSocket Manager in the ASP.NET Core dependency injection container. This will allow us to inject the WebSocket Manager into our controllers or other that require websocket management.

Step 3: Use WebSocket Manager

Finally, we can use the WebSocket Manager in our controllers or other components to manage websockets. We can inject the WebSocket Manager into our and use it to add or remove websockets.


By the steps outlined in this article, we can effectively solve the problem of disposing websockets in ASP.NET Core WebSocket Manager. Properly managing websocket connections is crucial for the performance and stability of web applications built with ASP.NET.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents