在异步回调中从 NetworkStream 读取缓冲区

Read buffer from NetworkStream in async callback

另见 Understand the NetworkStream.EndRead() example from MSDN

我正在尝试使用 BeginReadEndRead 方法从 NetworkStream 中异步读取(具体来说,我想打开一个 NetworkStream,执行各种其他任务,然后处理已处理的数据在 NetworkStream 上接收)。 EndRead (here) 的 MSDN 示例存在各种问题,并且无法正常工作,如链接问题中所述。该问题的答案显示了基本代码的结构,但不包括在回调中从 NetworkStream 实际读取数据。

在回调函数中,如何将从NetworkStream读取的数据传输到缓冲区?

编辑

这是原始的 MSDN 示例。

public static void myReadCallBack(IAsyncResult ar )
{
    NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;
    byte[] myReadBuffer = new byte[1024];
    String myCompleteMessage = "";
    int numberOfBytesRead;

    numberOfBytesRead = myNetworkStream.EndRead(ar);
    myCompleteMessage = String.Concat(myCompleteMessage,Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));    

    // message received may be larger than buffer size so loop through until you have it all.
    while(myNetworkStream.DataAvailable)
    {
        myNetworkStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length, new AsyncCallback(NetworkStream_ASync_Send_Receive.myReadCallBack), myNetworkStream);  
    }

    // Print out the received message to the console.
    Console.WriteLine("You received the following message : " + myCompleteMessage);
}

此示例的基本问题是没有数据从 NetworkStream 传输到 myReadBuffer

编辑 1

感谢 Dmytro Mukalov,以下代码有效:

internal class CallbackArgs
{
    public NetworkStream Stream { get; set; }
    public byte[] Buffer { get; set; }

    public CallbackArgs(NetworkStream stream, byte[] buffer)
    {
        Stream = stream;
        Buffer = buffer;
    }
}

//  In the caller:

    //  (Create and open thisNetworkStream, and check thisNetworkStream.CanRead)

    byte[] thisReadBuffer = new byte[1024];
    CallbackArgs args = new CallbackArgs(thisNetworkStream, thisReadBuffer);
    thisNetworkStream.BeginRead(thisReadBuffer, 0, thisReadBuffer.Length, new AsyncCallback(myReadCallBack), args);

//  The callback function:
public static void myReadCallBack(IAsyncResult ar)
{
    CallbackArgs args = (CallbackArgs)ar.AsyncState;
    NetworkStream myNetworkStream = args.Stream;
    byte[] myReadBuffer = args.Buffer;

    //  myReadBuffer now contains the data read from the network stream.

    int bytesRead = myNetworkStream.EndRead(ar);

    //  Do work on myReadBuffer, etc.
}

执行回调时,数据已传输到传递给前面的 BeginRead 调用的缓冲区中。给定示例的问题是它试图使用本地 myReadBuffer 缓冲区来读取初始消息。相反,您应该使传递给 BeginRead 的缓冲区可用于 EndRead。您可以通过使它成为此缓冲区的 class 的实例成员,通过将其与 NetworkStream 作为 BeginReadstate 参数一起传递,在某些方法中使用闭包变量来实现这将启动阅读循环等