title: Finding WebSocket Server memory leak
body: <p>Hello guys i am currently testing a websocket server written in Asp .Net Core 2.0 and i believe i have a memory leak.I can not find it even though i have tried to dispose everything that might be a concern.<br>The tests were done consecutively and the value of the ram is taken when it reaches stability.(this varies from 5 sec to 20 sec).<br>
  The occupied Ram is measured with plain Task Manager Monitor.<br><br><strong>The testing tool</strong>:<br>  <code>Thor</code> :  <a href="https://github.com/observing/thor" rel="nofollow noreferrer">https://github.com/observing/thor</a><br>
   The command : <code>thor --amount [amount] ws://[HostIP (localhost)]:[portnumber]</code><br></p>
  
  <p><strong>Results</strong>:</p>
  
  <pre><code>Connections | RAM Consumed at the end of test (GB):
  
  0             4.54
  50            4.55
  100           4.55
  150           4.61
  200           4.68
  300           4.76  
  400           4.59
  400           4.59
  500           4.62
  500           4.65
  550           4.65
  </code></pre>
  
  <p><strong>The WebSocket Server:</strong></p>
  
  <p><strong>SocketMiddleware</strong> -used by the appbuilder:</p>
  
  <pre><code>public class SocketMiddleware
      {
          public  byte[] ToSegment(string message) =&gt; System.Text.Encoding.UTF8.GetBytes(message);
          ClientTracker clientTracker; //the socket clients tracker this is the object we're speaking of
          RequestDelegate next;
          public SocketMiddleware(ClientTracker tracker,RequestDelegate del)
          {
              this.clientTracker=tracker;
              this.next=del;   
          }
          public async Task Invoke(HttpContext context)
          {
              if(!context.WebSockets.IsWebSocketRequest)
              {
                  await this.next.Invoke(context);
                  return;
              }
              await this.clientTracker.AddClient(context.WebSockets);
  
          }
      }
  </code></pre>
  
  <p><strong>SocketTracker</strong>- this is the suspect which is dealing with all the opened sockets</p>
  
  <pre><code>  public class ClientTracker
          {
              ConcurrentDictionary&lt;string, Client&gt; clientMap = new ConcurrentDictionary&lt;string, Client&gt;();
  
              public string CreateConnectionID() =&gt; Guid.NewGuid().ToString();
              public string GetIDOfSocket(WebSocket socket) =&gt; this.clientMap.First(x =&gt; x.Value.webSocket.Equals(socket)).Key;
              public Client GetClientByID(string id)
              {
                  this.clientMap.TryGetValue(id, out Client client);
                  return client;
              }
              public async Task AddClient(WebSocketManager manager)
              {
                 using (WebSocket socket = await manager.AcceptWebSocketAsync())
                 {
                   Client newClient = Client.CreateClient(socket, CreateConnectionID());
                   if(clientMap.TryAdd(newClient.clientID, newClient))
                   {
                     await ReceiveMessage(newClient);
                   }
  
                  }
               }
  
              public async Task ReceiveMessage(Client client)
              {
                  while (client.webSocket.State == WebSocketState.Open)
                  {
                      WebSocketReceiveResult result = await client.ReceiveResult();
                      //dosomething with result...
                      if (result.MessageType == WebSocketMessageType.Close)
                      {
                          await client.webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client closed", CancellationToken.None);
                          break;
                      }
                      //send custom message 
                      await client.SendMessage("lala");
                  }
              }
          }
  </code></pre>
  
  <p><strong>Client</strong>- socketWrapper which performs all required operations on the socket and stores temporary data to be used by the tracker</p>
  
  <pre><code>public class Client
      {
          //Fields
          public readonly WebSocket webSocket;
          public readonly string clientID;
          public StringBuilder tempData;
          //Auxiliary
          private const int BufferSize = 1024 * 4;
  
          public static Client CreateClient(WebSocket socket, string id)
          {
              Client client = new Client(socket, id);
              return client;
          }
  
          public Client(WebSocket socket, string id)
          {
              this.webSocket = socket;
              this.clientID = id;
              tempData = new StringBuilder();
          }
          public async Task&lt;WebSocketReceiveResult&gt; ReceiveResult()
          {
              tempData.Clear();
              ArraySegment&lt;byte&gt; segment = new ArraySegment&lt;byte&gt;(new byte[BufferSize]);
              WebSocketReceiveResult result = await this.webSocket.ReceiveAsync(segment, CancellationToken.None);
              tempData.Append(BitConverter.ToString(segment.Array));
              return result;
          }
  
          public async Task SendMessage(string message)
          {
              byte[] bytes = Encoding.UTF8.GetBytes(message);
              await this.webSocket.SendAsync(new ArraySegment&lt;byte&gt;(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
          }
  
      }
  </code></pre>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
          {
              services.AddMvc();
              services.AddSingleton&lt;ClientTracker&gt;();
          }
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              app.UseWebSockets();
              app.UseMiddleware&lt;SocketMiddleware&gt;();
          }
  </code></pre>
  
  <p>P.S:
  The server was not closed between requests.Could it be the concurrent dictionary ?Besides it, the reference of the Client is cleaned ,the Client is disposed,and the socket is closed.The string builder can not be disposed,and the Tracker/Middleware live as long as the app lives.</p>