I am creating a little app based on TCP connections. For that, I have to create as many "listeners" as ports I have.
I need to be constantly listening for new messages, so I created a for loop with all the listeners.
public void ListenDataAsync(int[] ports)
{
IPAddress ipAddress = IPAddress.Parse(Constants.host);
/*Create the Clients*/
List<Task> tasks = new List<Task>();
for (var i = 0; i < ports.Length; i++)
{
tcpListeners[i] = new TcpListener(ipAddress, ports[i]);
tcpListeners[i].Start();
var t = Task.Run(() => 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("Waiting for a connection...");
// 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();
}
}
In my case, I have two ports, so two listeners will be created.
With threads, the concurrency works properly, but I want to use Tasks instead of Threads.
What mainly happens, is that the message "Waiting for a connection" is not always disposed properly. It must be displayed twice... Sometimes it appears once, none, or twice.
Does someone know which could be the cause?
It seems to be something related with tasks...
Thanks in advance :)
You only need to do:
await Task.Run(() => DoBeginAcceptTcpClient(tcpListeners[i])