套接字BeginAcceptSocket与Task.Run

时间:2019-02-21 04:06:05

标签: c# .net asynchronous task

我有两个选择:

  1. 同步接受套接字,然后处理新任务:
while (true) {
    var socket = tcpListener.Accept();
    Task.Run(async () => await RunConnectionAsync(socket));
}
  1. 异步接受套接字,接受回调时为进程套接字
while (true)
{
    allDone.Reset();
    tcpListener.BeginAcceptSocket(AcceptCallback, tcpListener);
    allDone.WaitOne();
}

private static void AcceptCallback(IAsyncResult result)
{
    allDone.Set();

    var listener = (TcpListener)result.AsyncState;
    var socket = listener.EndAcceptSocket(result);

    ProcessSocket(socket);
}

就性能而言,哪种解决方案更好?

0 个答案:

没有答案