什么是异步方法调用的优势?

0 .net asynchronous

仅使用.net套接字作为示例,我使用:

TcpListener listener = new TcpListener(ip, port);
while(true)
{
    TcpClient client = socket.AcceptTcpClient();
    DoSomethingWithClient(client);
}
Run Code Online (Sandbox Code Playgroud)

但另一种方式似乎是(基于http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginaccepttcpclient.aspx):

public static ManualResetEvent tcpClientConnected = new ManualResetEvent(false);

public static void DoBeginAcceptTcpClient(TcpListener listener)
{
    tcpClientConnected.Reset();
    listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
    tcpClientConnected.WaitOne();
}

public static void DoAcceptTcpClientCallback(IAsyncResult ar) 
{
    TcpListener listener = (TcpListener) ar.AsyncState;
    TcpClient client = listener.EndAcceptTcpClient(ar);
    DoSomethingWithClient(client);
    tcpClientConnected.Set();
}
Run Code Online (Sandbox Code Playgroud)

恕我直言,异步风格需要3倍的代码,看起来像goto spaghetti - 它难以阅读,并迫使你分离出相关的代码.那你为什么要使用异步方式呢?据推测它必须有一些优势?

Joe*_*oey 5

它的优点是不会阻塞调用者的线程,这在创建交互式应用程序时尤为重要,这些应用程序即使在执行工作时也应保持响应.

由于C#5有async/await做出这种代码更容易编写和阅读.