0

从我读过的内容来看,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
}
4

0 回答 0