title: TCP connection with Tasks (not Threads) with .net 5
body: <p>I am creating a little app based on TCP connections. For that, I have to create as many &quot;listeners&quot; as ports I have.</p>
  <p>I need to be constantly listening for new messages, so I created a for loop with all the listeners.</p>
  <pre><code>public void ListenDataAsync(int[] ports)
          {
              IPAddress ipAddress = IPAddress.Parse(Constants.host);
  
              /*Create the Clients*/
              List&lt;Task&gt; tasks = new List&lt;Task&gt;();
              for (var i = 0; i &lt; ports.Length; i++)
              {
                  tcpListeners[i] = new TcpListener(ipAddress, ports[i]);
  
                  tcpListeners[i].Start(); 
                  var t = Task.Run(() =&gt; DoBeginAcceptTcpClient(tcpListeners[i]));
                  Task.Delay(1000);
                  tasks.Add(t);
              }
              Task.WaitAll(tasks.ToArray());
              tasks.Clear();
          }
  
  private void DoBeginAcceptTcpClient(TcpListener listener)
          {
              if (listener != null)
              {
                  // Set the event to nonsignaled state.
                  tcpClientConnected.Reset();
  
                  // Start to listen for connections from a client.
                  Console.WriteLine(&quot;Waiting for a connection...&quot;);
  
                  // Accept the connection.
                  listener.Start();
                  // BeginAcceptSocket() creates the accepted socket.
                  listener.BeginAcceptTcpClient(
                      new AsyncCallback(DoAcceptTcpClientCallback),
                      listener);
  
                  // Wait until a connection is made and processed before continuing.
                  tcpClientConnected.WaitOne();
  
              }
          }
  </code></pre>
  <p>In my case, I have two ports, so two listeners will be created.</p>
  <p>With threads, the concurrency works properly, but <strong>I want to use Tasks instead of Threads</strong>.</p>
  <p>What mainly happens, is that the message &quot;Waiting for a connection&quot; is not always disposed properly. It must be displayed twice... Sometimes it appears once, none, or twice.</p>
  <p>Does someone know which could be the cause?</p>
  <p>It seems to be something related with tasks...</p>
  <p>Thanks in advance :)</p>