ConnectAsync
据我所知,没有对/ AcceptAsync
/ SendAsync
/等的内置(或框架扩展)支持ReceiveAsync
。我将如何编写自己的包装器来支持异步等待机制。例如,我当前的代码同时处理ReceiveAsyn
内联和回调(在 中指定SocketAsyncEventArgs
):
private void PostReceive(SocketAsyncEventArgs e)
{
e.SetBuffer(ReceiveBuffer.DataBuffer, ReceiveBuffer.Count, ReceiveBuffer.Remaining);
e.Completed += Receive_Completed;
// if ReceiveAsync returns false, then completion happened inline
if (m_RemoteSocket.ReceiveAsync(e) == false)
{
Receive_Completed(this, e);
}
}
.
private void Receive_Completed(object sender, SocketAsyncEventArgs e)
{
e.Completed -= Receive_Completed;
if (e.BytesTransferred == 0 || e.SocketError != SocketError.Success)
{
if (e.BytesTransferred > 0)
{
OnDataReceived(e);
}
Disconnect(e);
return;
}
OnDataReceived(e);
//
// we do not push the SocketAsyncEventArgs back onto the pool, instead
// we reuse it in the next receive call
//
PostReceive(e);
}