当前位置: 代码迷 >> .NET Framework >> socketasynceventargs的有关问题
  详细解决方案

socketasynceventargs的有关问题

热度:96   发布时间:2016-05-02 01:03:56.0
socketasynceventargs的问题
msdn上的示例:
C# code
public void StartAccept(SocketAsyncEventArgs acceptEventArg)    {        if (acceptEventArg == null)        {            acceptEventArg = new SocketAsyncEventArgs();            acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);        }        else        {            // socket must be cleared since the context object is being reused            acceptEventArg.AcceptSocket = null;        }        m_maxNumberAcceptedClients.WaitOne();        bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);        if (!willRaiseEvent)        {            ProcessAccept(acceptEventArg);        }    }    private void ProcessAccept(SocketAsyncEventArgs e)    {        Interlocked.Increment(ref m_numConnectedSockets);        Console.WriteLine("Client connection accepted. There are {0} clients connected to the server",            m_numConnectedSockets);        // Get the socket for the accepted client connection and put it into the         //ReadEventArg object user token        SocketAsyncEventArgs readEventArgs = m_readWritePool.Pop();        ((AsyncUserToken)readEventArgs.UserToken).Socket = e.AcceptSocket;        // As soon as the client is connected, post a receive to the connection        bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs);        if(!willRaiseEvent){            ProcessReceive(readEventArgs);        }        // Accept the next connection request        StartAccept(e);    }


StartAccept方法里调用listenSocket.AcceptAsync(acceptEventArg),如果返回值是false则是同步完成,下面就需要接着同步调用ProcessAccept(acceptEventArg)。 在ProcessAccept方法里调用e.AcceptSocket.ReceiveAsync(readEventArgs)若也是同步完成的话,又要再调用StartAccept方法。

请问这样不是循环调用了吗?有点困惑,请高人解答。

------解决方案--------------------
是的。这里是递归。

不过大部分时候是异步的,并不总是能够同步,所以递归的深度其实不会太深。