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

发布于 2024-10-17 15:55:21 字数 1184 浏览 6 评论 0原文

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

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 ReceiveAsync 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);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少跟Wǒ拽 2024-10-24 15:55:21

诀窍是使用 TaskCompletionSource 来处理这种情况。

我在博客上谈到了这一点。有关详细信息,请参阅 为 Await 准备现有代码

The trick is to use TaskCompletionSource to handle this scenario.

I blogged about this. For details, see Preparing Existing code For Await.

巴黎盛开的樱花 2024-10-24 15:55:21

您还可以编写一个自定义等待,在这种情况下我更喜欢它。这是 Microsoft 的 Stephen Toub 提出的一项技术。您可以在此处阅读有关此技术的更多信息。
http://blogs.msdn.com/b/pfxteam /archive/2011/12/15/10248293.aspx

这是自定义的可等待:

public sealed class SocketAwaitable : INotifyCompletion
{
    private readonly static Action SENTINEL = () => { };
    internal bool m_wasCompleted;
    internal Action m_continuation;
    internal SocketAsyncEventArgs m_eventArgs;
    public SocketAwaitable(SocketAsyncEventArgs eventArgs)
    {
        if (eventArgs == null) throw new ArgumentNullException("eventArgs");
        m_eventArgs = eventArgs;
        eventArgs.Completed += delegate
        {
            var prev = m_continuation ?? Interlocked.CompareExchange(
                ref m_continuation, SENTINEL, null);
            if (prev != null) prev();
        };
    }
    internal void Reset()
    {
        m_wasCompleted = false;
        m_continuation = null;
    }
    public SocketAwaitable GetAwaiter() { return this; }
    public bool IsCompleted { get { return m_wasCompleted; } }
    public void OnCompleted(Action continuation)
    {
        if (m_continuation == SENTINEL ||
            Interlocked.CompareExchange(
                ref m_continuation, continuation, null) == SENTINEL)
        {
            Task.Run(continuation);
        }
    }
    public void GetResult()
    {
        if (m_eventArgs.SocketError != SocketError.Success)
            throw new SocketException((int)m_eventArgs.SocketError);
    }
}

添加到套接字类并使其方便的一些扩展方法:

public static class SocketExtensions
{
    public static SocketAwaitable ReceiveAsync(this Socket socket,
        SocketAwaitable awaitable)
    {
        awaitable.Reset();
        if (!socket.ReceiveAsync(awaitable.m_eventArgs))
            awaitable.m_wasCompleted = true;
        return awaitable;
    }
    public static SocketAwaitable SendAsync(this Socket socket,
        SocketAwaitable awaitable)
    {
        awaitable.Reset();
        if (!socket.SendAsync(awaitable.m_eventArgs))
            awaitable.m_wasCompleted = true;
        return awaitable;
    }
    // ... 
}

在使用中:

    static async Task ReadAsync(Socket s)
    {
        // Reusable SocketAsyncEventArgs and awaitable wrapper 
        var args = new SocketAsyncEventArgs();
        args.SetBuffer(new byte[0x1000], 0, 0x1000);
        var awaitable = new SocketAwaitable(args);

        // Do processing, continually receiving from the socket 
        while (true)
        {
            await s.ReceiveAsync(awaitable);
            int bytesRead = args.BytesTransferred;
            if (bytesRead <= 0) break;

            Console.WriteLine(bytesRead);
        }
    }

You can also write a custom awaitable, which I like better in this situation. This is a technique by Stephen Toub from Microsoft. You can read more about this technique here.
http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx

Here is the custom awaitable:

public sealed class SocketAwaitable : INotifyCompletion
{
    private readonly static Action SENTINEL = () => { };
    internal bool m_wasCompleted;
    internal Action m_continuation;
    internal SocketAsyncEventArgs m_eventArgs;
    public SocketAwaitable(SocketAsyncEventArgs eventArgs)
    {
        if (eventArgs == null) throw new ArgumentNullException("eventArgs");
        m_eventArgs = eventArgs;
        eventArgs.Completed += delegate
        {
            var prev = m_continuation ?? Interlocked.CompareExchange(
                ref m_continuation, SENTINEL, null);
            if (prev != null) prev();
        };
    }
    internal void Reset()
    {
        m_wasCompleted = false;
        m_continuation = null;
    }
    public SocketAwaitable GetAwaiter() { return this; }
    public bool IsCompleted { get { return m_wasCompleted; } }
    public void OnCompleted(Action continuation)
    {
        if (m_continuation == SENTINEL ||
            Interlocked.CompareExchange(
                ref m_continuation, continuation, null) == SENTINEL)
        {
            Task.Run(continuation);
        }
    }
    public void GetResult()
    {
        if (m_eventArgs.SocketError != SocketError.Success)
            throw new SocketException((int)m_eventArgs.SocketError);
    }
}

Some extension methods to add to the socket class and make it convenient:

public static class SocketExtensions
{
    public static SocketAwaitable ReceiveAsync(this Socket socket,
        SocketAwaitable awaitable)
    {
        awaitable.Reset();
        if (!socket.ReceiveAsync(awaitable.m_eventArgs))
            awaitable.m_wasCompleted = true;
        return awaitable;
    }
    public static SocketAwaitable SendAsync(this Socket socket,
        SocketAwaitable awaitable)
    {
        awaitable.Reset();
        if (!socket.SendAsync(awaitable.m_eventArgs))
            awaitable.m_wasCompleted = true;
        return awaitable;
    }
    // ... 
}

In use:

    static async Task ReadAsync(Socket s)
    {
        // Reusable SocketAsyncEventArgs and awaitable wrapper 
        var args = new SocketAsyncEventArgs();
        args.SetBuffer(new byte[0x1000], 0, 0x1000);
        var awaitable = new SocketAwaitable(args);

        // Do processing, continually receiving from the socket 
        while (true)
        {
            await s.ReceiveAsync(awaitable);
            int bytesRead = args.BytesTransferred;
            if (bytesRead <= 0) break;

            Console.WriteLine(bytesRead);
        }
    }
╰沐子 2024-10-24 15:55:21

对于套接字内容,.NET 4.5 中有一个包装器。如果您使用 .NET 4,我建议您使用 APM,而不是基于事件的异步模式。它更容易转换为Task

For socket stuff there is a wrapper in .NET 4.5. If you are on .NET 4 I'd recommend to use the APM and not the event-based asynchronous pattern. It converts to Task's far more easily.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文