c# - 如何为异步等待调用创建包装器?

标签 c# asynchronous async-await

据我所知,ConnectAsync 没有内置(或框架扩展)支持/AcceptAsync/SendAsync/ReceiveAsync ,等等。我将如何编写自己的包装器,该包装器将由异步等待机制支持。例如,我当前处理 ReceiveAsyn 的代码c 内联和回调(在 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来处理这种情况。

我写了关于这个的博客。有关详细信息,请参阅 Preparing Existing code For Await .

关于c# - 如何为异步等待调用创建包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5007106/

相关文章:

java - 序列设计模式中的流程

c# - 具有无参数构造函数的 NUnit TestFixture

c# - 处理不正确的 HTTP header 正文大小值?

javascript - 我可以在 Angular 的 Promise 链中调用函数吗

java - ThreadPoolExecutor 中的核心池大小与最大池大小

java - 在 Java 中使异步 Web 服务调用成为同步调用

队列或等待列表中的 C# 异步任务

javascript - 自动执行异步函数

javascript - 在Typescript中使用异步方法链接(只是找到了解决方案)

c# - ASP核心: Azure Ad Auth + custom JWT + custom Identity store