1

From what I've read, beginReceive is considered superior to receive in almost all cases (or all?). This is because beginReceive is asynchronous and waits for data to arrive on a seperate thread, thereby allowing the program to complete other tasks on the main thread while waiting.

But with beginReceive, the callback function still runs on the main thread. And so there is overhead with switching back and forth between the worker thread and the main thread each time data is received. I know the overhead is small, but why not avoid it by simply using a separate thread to host a continuous loop of receive calls?

Can someone explain to me what is inferior about programming with the following style:

static void Main() 
{
  double current_temperature = 0; //variable to hold data received from server
  Thread t = new Thread (UpdateData);      
  t.start();

  // other code down here that will occasionally do something with current_temperature
  // e.g. send to a GUI when button pressed
  ... more code here
}

static void UpdateData()
{
  Socket my_socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  my_socket.Connect (server_endpoint);
  byte [] buffer = new byte[1024];

  while (true)
    my_socket.Receive (buffer); //will receive data 50-100 times per second

    // code here to take the data in buffer 
    // and use it to update current_temperature
    ... more code here
  end
}
MikeD
  • 171
  • 2
  • 13
  • Threads are **expensive** in Windows. Each thread created has its own 1MB stack allocated, for example. And waiting on IO is a waste of a thread because it will be blocked 99% of the time. This is why high-performance IO-blocked software (e.g. NodeJS) tends to use few threads and async IO. – Dai Mar 26 '18 at 02:26
  • 2
    I recommend reading this: https://stackoverflow.com/questions/42847851/on-windows-c-does-socket-beginreceive-take-a-background-thread-before-or-af – Dai Mar 26 '18 at 02:31
  • @Dai thanks, that is helpful. Is there a point when it would make sense to do a separate thread? For instance, if I will be receiving data thousands of time per second? – MikeD Mar 26 '18 at 02:43
  • Only in simple, toy-grade programs that won't see production use. Internally Windows always uses async IO - the synchronous API is actually an abstraction, and abstractions have cost. Just dive-in to the async APIs and don't look back. – Dai Mar 26 '18 at 02:52

0 Answers0