7

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

3 回答 3

3

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

我在博客上写过这个。有关详细信息,请参阅为 Await 准备现有代码

于 2011-02-15T17:32:41.290 回答
2

你也可以编写一个自定义的 awaitable,在这种情况下我更喜欢它。这是来自 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);
        }
    }
于 2012-09-03T21:51:12.433 回答
0

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

于 2012-09-03T22:03:08.167 回答