如何在等待请求时避免阻塞.NET线程

时间:2014-10-01 17:52:44

标签: c# .net sockets

我有一个正在监听System.Net.Sockets.Socket的服务器应用程序。它会阻塞Socket.Accept(),占用线程。什么是放弃对线程的控制,然后将计算结果产生给调用客户端的好方法?

服务器代码有点清理,如下所示:

void ManeLupe(Socket socket)
{
    for (;;)
    {
        Socket client = null;
        NetworkStream stm = null;
        try 
        {
            client = socket.Accept();             // Blocks thread
            stm = new NetworkStream(client);
            var response = ProcessRequest(stm);   // this could take a while
            WriteResponse(response, stm);
        }
        catch (Exception ex)
        {
            LogError(client, ex);
        }
        finally
        { 
            if (stm != null) stm.Dispose();
            if (client != null) client.Dispose();
        }
    }
}

目前,我的约束是代码必须在.NET framework 3.5上运行,因此我无法利用新的Task<>async优势。坦率地说,我对异步编程很新,我怀疑这将是这个查询的答案。

2 个答案:

答案 0 :(得分:2)

Socket提供了名为BeginAccept的Accept的异步变体,这就是你所追求的。

BeginAccept是Accept的APM实现,它为每个操作提供了一对方法。在这种情况下,您将使用BeginAcceptEndAccept

正如@CoryNelson的评论中所述,您也可以考虑使用AcceptAsync。你可以选择哪一个。

答案 1 :(得分:0)

     You can use AcceptAsync and register to the callback to do your processing after the accept is completed. Simple example below

           void ManeLupe(Socket socket)
            {

                var args = new SocketAsyncEventArgs();
                args.Completed += Accept_Completed;
                socket.AcceptAsync(args);
            }

            void Accept_Completed(object sender, SocketAsyncEventArgs e)
            {
                //do your processing here
            }
相关问题