在同一台服务器上组合同步和异步套接字调用是否被认为是不好的做法?例如(从 msdn 修改):
// Initalize everything up here
while (true) {
// Set the event to nonsignaled state.
allDone.Reset(); //allDone is a manual reset event
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
public static void AcceptCallback(IAsyncResult ar) {
// Signal the main thread to continue.
allDone.Set();
// Handle the newly connected socket here, in my case have it
// start receiving data asynchronously
}
在这种情况下,因为您要等到每个连接都建立后才能侦听下一个连接,所以这似乎是一个阻塞调用。鉴于它应该更快一点,因为客户端的初始处理将在不同的线程中完成,但理论上这应该是一个相对较小的开销。
鉴于此,执行以下操作是否会被视为不好的做法:
while (true) {
// Start listening for new socket connections
Socket client = listener.Accept(); // Blocking call
// Handle the newly connected socket here, in my case have it
// start receiving data asynchronously
}
在我看来,这段代码比上面的代码要简单得多,如果我是正确的,它的性能也应该与上面的代码比较接近。