我正在尝试用 C# 编写一段代码以异步读取 TcpClient 。这是我的代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
class Connection
{
private TcpClient socket;
private NetworkStream socketStream;
private byte[] buffer;
private int bytesRead;
private Task<int> readTask;
public Connection(TcpClient socket)
{
this.socket = socket;
socketStream = socket.GetStream();
buffer = new byte[4096];
readTask = Task.Factory.FromAsync<byte[], int, int, int>(
this.socketStream.BeginRead
, this.socketStream.EndRead
, this.buffer
, 0
, this.buffer.Length
, null
);
readTask.ContinueWith(
(task) => {
this.bytesRead = (int)task.Result;
//Do something with buffer.
}
, TaskContinuationOptions.OnlyOnRanToCompletion
);
}
}
问题是异步 BeginRead 将尝试覆盖 Connection 对象的缓冲区,一旦新数据到达,无论是否使用旧数据,都会覆盖旧数据。我应该如何解决这个问题?AFAIK 它应该与闭包有关,但我不知道怎么做!