1

您好我正在尝试创建一个 TAP 包装器。ConnectTaskAsync 很好,但是我在使用 SendTaskAsync 时遇到了一些困难。

public static Task ConnectTaskAsync(this Socket socket, EndPoint endpoint)
        {
            return Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, endpoint, null);
        }

    public static Task<int> SendTaskAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags)
    {
        return Task<int>.Factory.FromAsync(socket.BeginSend, buffer, offset, size, flags, socket.EndSend, null);
    }

我得到的错误是下面BeginSend带有红色下划线的消息 Expected a method with IAsyncResult BeginSend

我哪里做错了?

4

1 回答 1

1

You have your FromAsync defined incorrectly. Unfortunately, there isn't an overload of FromAsync which accepts 4 separate arguments (which would be required for BeginSend), so you'll need to use a different overload:

public static Task<int> SendTaskAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags)
{
    AsyncCallback nullOp = (i) => {};
    IAsyncResult result = socket.BeginSend(buffer, offset, size, flags, nullOp, socket);
    // Use overload that takes an IAsyncResult directly
    return Task.Factory.FromAsync(result, socket.EndSend);
}
于 2013-07-04T16:27:46.370 回答