【发布时间】:2010-10-22 20:18:52
【问题描述】:
在同一台服务器上结合同步和异步套接字调用是否被认为是不好的做法?例如(修改自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
}
在我看来,这段代码比上面的代码要简单得多,如果我没记错的话,性能也应该与上面的代码比较接近。
【问题讨论】:
标签: c# sockets asynchronous synchronous