TcpClient から非同期的に読み取るコードを C# で記述しようとしています。これが私のコードです:
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 オブジェクトのバッファを上書きしようとし、新しいデータが到着すると、それが消費されたかどうかに関係なく、古いデータが上書きされることです。この問題にどのように取り組むべきですか?私の知る限り、クロージャーと関係があるはずですが、その方法がわかりません!