.NET套接字:beginReceive与带接收的专用线程

时间:2018-03-26 02:21:21

标签: c# multithreading sockets receiver beginreceive

据我所知, beginReceive 几乎在所有情况下都被认为优于 接收 (或所有?)。这是因为 beginReceive 是异步的并且等待数据到达单独的线程,从而允许程序在等待时完成主线程上的其他任务。

但是使用 beginReceive ,回调函数仍然在主线程上运行。因此,每次接收数据时,在工作线程和主线程之间来回切换都会产生开销。我知道开销很小,但为什么不通过简单地使用一个单独的线程来承载连续的接收呼叫循环来避免它?

有人可以向我解释一下使用以下样式编程的不足之处:

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
}

0 个答案:

没有答案