0

I want to rephrase my previous question Should I replace all my "new Thread" with "Task.Factory.StartNew"?

I need to listen for several udp sockets

................
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
........

public void Receive()
{
    byte[] buffer = new byte[65536];
    while (true)
    {
        try
        {
            count = s.Receive(buffer);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return;
        }
        if (count > 0)
        {
            OnNewDatagram(new NewDatagramEventArgs(buffer, count));
        }
    }
}

So I need to launch several "Receive()" methods (one for each socket). Now I'm using one Thread for one socket:

socketA = new...
....
threadA = new Thread(Receive);
.....
threadA.Start();

socketB = new...
....
threadB = new Thread(Receive);
.....
threadB.Start();

What should I use:

  • one thread for one socket
  • one thread for all sockets(how?)
  • one task for all sockets
  • one task for one socket
  • other?

upd I have only 2-3 sockets, so it's probably better to use one-socket-one-thread model instead of Socket.Select... or one-socket-one-task model?

Community
  • 1
  • 1
Oleg Vazhnev
  • 23,239
  • 54
  • 171
  • 305

2 Answers2

1

You should use Socket.Select to wait on several sockets and handle incoming data on any of them.

zmbq
  • 38,013
  • 14
  • 101
  • 171
  • why it's better than using one-thread-per-socket model? from article it is not clear that `Socket.Select` is better... – Oleg Vazhnev Mar 16 '12 at 10:52
  • Well, because you don't have on thread per socket. Threads are costly, and in your case most of the time they'll just wait for sockets. You'll get the same I/O performance without the additional threads. – zmbq Mar 16 '12 at 11:48
0

The way I see it, you should use a new thread for each socket, because if you use the same thread for all the sockets, you would only get one stream, the one that got first.

Adrian Matteo
  • 987
  • 1
  • 10
  • 28