问题描述
据我所知,没有对 ConnectAsync
/ AcceptAsync
/ SendAsync
/ ReceiveAsync 等.我将如何编写自己的包装程序,该包装程序将受到async-await机制的支持.例如,我当前的代码同时处理内联和回调上的 ReceiveAsyn
c(在 SocketAsyncEventArgs
中指定):
From what I can tell, there is no built-in (or framework extension) support for ConnectAsync
/AcceptAsync
/SendAsync
/ReceiveAsync
, etc.. How would I write my own wrapper that would be supported by the async-await mechanism. For example, my current code which handles a ReceiveAsyn
c both inline and on the callback (which is specified in the 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);
}
推荐答案
诀窍是使用 TaskCompletionSource 来处理这种情况.
The trick is to use TaskCompletionSource to handle this scenario.
我对此发表了博客.有关详细信息,请参见准备等待的现有代码.
I blogged about this. For details, see Preparing Existing code For Await.
这篇关于如何为异步等待调用创建包装器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!