Search code examples
c#arrayslistsocketsmulticast

Send data to all sockets at exact time


Say we have array or list of sockets named (A,B,C) and we want to send data to all of them at the same exact time due to that the application is really time critical, then is there a away to send to all of them without iteration? as with iteration then "C" received messages will be always delayed compared to "A" for example.

...

UPDATE:

Paralle.ForEach did the job with 3-4 times faster that normal foreach, here is a benchmark with 20 tries for sending to 5000 sockets:

enter image description here


Solution

  • As far as I know (and I could be wrong), you can use Parallel.Foreach() from System.Threading.Tasks so you can execute or process each iteration concurrently.

    For example let's say you have a List<Socket> sockets and some dataToSend:

     Parallel.ForEach(sockets, socket =>
            {
                try
                {
                    socket.Send(dataToSend);
                    Console.WriteLine($"Data sent on thread {Task.CurrentId}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            });