我使用的SocketAsyncEventArgs看着一个服务器的源代码,我试图找出如何这会不会导致堆栈溢出:这不会导致堆栈溢出?
所以这段代码被称为允许插座接受传入连接(向下滚动至底部,明白我的意思):
/// <summary>
/// Begins an operation to accept a connection request from the client.
/// </summary>
/// <param name="acceptEventArg">The context object to use when issuing
/// the accept operation on the server's listening socket.</param>
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted);
}
else
{
// Socket must be cleared since the context object is being reused.
acceptEventArg.AcceptSocket = null;
}
this.semaphoreAcceptedClients.WaitOne();
Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
this.ProcessAccept(acceptEventArg);
}
}
然后这个代码被调用一次的连接实际上是接受(见最后一行):
/// <summary>
/// Process the accept for the socket listener.
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
private void ProcessAccept(SocketAsyncEventArgs e)
{
if (e.BytesTransferred > 0)
{
Interlocked.Increment(ref this.numConnectedSockets);
Console.WriteLine("Client connection accepted. There are {0} clients connected to the server",
this.numConnectedSockets);
}
// Get the socket for the accepted client connection and put it into the
// ReadEventArg object user token.
SocketAsyncEventArgs readEventArgs = this.readWritePool.Pop();
readEventArgs.UserToken = e.AcceptSocket;
// As soon as the client is connected, post a receive to the connection.
Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs);
if (!willRaiseEvent)
{
this.ProcessReceive(readEventArgs);
}
// Accept the next connection request.
this.StartAccept(e); // <==== tail end recursive?
}
看看最后一个线。它再次调用顶层函数。这是如何通过在这两个函数之间来回跳动来溢出堆栈的?这似乎是尾端递归,但这不是Haskell,所以我不明白这是如何工作的。
这是我的理解,这些不是在线程中被解雇,而是由cpu一次执行一个。