1

我正在尝试从 TcpClient 连续读取数据。这是我的代码片段。

var task = Task.Factory.StartNew(Read);

task.ContinueWith(ant =>
     Console.WriteLine("Error: " + ant.Exception.Message),
     TaskContinuationOptions.OnlyOnFaulted);

task.ContinueWith(ant =>
     {
         Log("Log my data");
     });


void Read()   
{
   Task<int> readChunk = Task<int>.Factory.FromAsync(
              _stream.BeginRead, _stream.EndRead,
              data, bytesRead, data.Length - bytesRead, null,
              TaskCreationOptions.AttachedToParent);

   readChunk.ContinueWith(rt => { bytesRead = readChunk.Result; }, TaskContinuationOptions.NotOnFaulted
                                            | TaskContinuationOptions.AttachedToParent);
}

这段代码运行良好,但流中可能会有更多数据,所以我希望它返回并再次读取。开始另一个读取任务似乎不正确。我不熟悉任务并行库。通常我会写这样的东西:

while (true)
{
   bytesRead += _stream.Read(data, bytesRead, chunkSize);
   if(bytesRead == BytesExpected)
       break;
}
4

0 回答 0