c# - 在一个线程中发送数据是错误的吗?
问题描述
我想在一个线程中发送数据,首先我将数据排入并发队列,如果发送线程循环发送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);
}
}
但是在客户端,我收到的数据是乱码,这样写有错吗?
解决方案
因为不能保证所有线程都将按顺序执行,所以您需要定义一个可以告诉数据序列号的结构
private ConcurrentQueue<(int, byte[])> sendBuffers;
该int
组件将是数据的索引,一旦获得所有结果,您需要根据该索引对列表进行排序以恢复数据的顺序。
int index = 0;
while (...)
{
...
sendBuffers.Enqueue((index, bytesToSend)); // enqueue the data with its index
index++;
}
推荐阅读
- android - Google 的 ARCore 是否/可以在 Kindle 上运行?
- sqlite - 更改表 SQLLITE
- ios - 使用 AVQueuePlayer ios swift 在控制器中未调用接近传感器通知
- offset - 什么是 NTP 服务器中的时钟偏移
- c# - 除了使用自适应卡片之外,有没有办法在 V4 聊天机器人 C# 中启用日历选项作为输入?
- rpgle - 使用小数从字母转换为数字失败
- shopify - 如何在 Shopify 中为管理员添加自定义菜单?
- anki - 在 iOS Anki 应用程序上捕获“输入答案”类型的输入字段
- grouping - Clickhouse - 在嵌套列中分组
- python - Visual Studio Code - Python - List Index Limit Max 300 - 调试器