首页 > 解决方案 > 在一个线程中发送数据是错误的吗?

问题描述

我想在一个线程中发送数据,首先我将数据排入并发队列,如果发送线程循环发送concurrentqueue.count >0

private ConcurrentQueue < byte[] > sendBuffers;
private ManualResetEvent waitEvent = new ManualResetEvent(false);
public void Send(byte[] data) {
  sendBuffers.Enqueue(data);
  waitEvent.Set();
}

public void SendFile(string fileName) {
  using(FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read)) {
    int count = 0;
    byte[] buffer = new byte[Const.NetDataSize];
    while ((count = fs.Read(buffer, 0, Const.NetDataSize)) > 0) {
      byte[] bytesToSend = new byte[count];
      Buffer.BlockCopy(buffer, 0, bytesToSend, 0, count);
      sendBuffers.Enqueue(bytesToSend);
    }
  }
  waitEvent.Set();
}
public async void Start() {
  await Task.Run(ProcessSend);
}

private async void ProcessSend() {
  if (sendBuffers.Count <= 0) {
    Console.WriteLine("Total Send " + count + " bytes");
    waitEvent.Reset();
  }

  waitEvent.WaitOne();
  byte[] buffer;
  sendBuffers.TryDequeue(out buffer);
  try {
    count += buffer.Length;
    await stream.CancelableWriteAsync(buffer, 0, buffer.Length, source.Token);
    ProcessSend();
  } catch (Exception ex) {
    Console.WriteLine("send exception: " + ex.Message);
  }
}

但是在客户端,我收到的数据是乱码,这样写有错吗?

标签: c#

解决方案


因为不能保证所有线程都将按顺序执行,所以您需要定义一个可以告诉数据序列号的结构

private ConcurrentQueue<(int, byte[])> sendBuffers;

int组件将是数据的索引,一旦获得所有结果,您需要根据该索引对列表进行排序以恢复数据的顺序。

    int index = 0;
    while (...)
    {
        ...
        sendBuffers.Enqueue((index, bytesToSend)); // enqueue the data with its index
        index++;
    }

推荐阅读