【发布时间】:2019-10-04 14:29:36
【问题描述】:
我正在逐字节读取和解码二进制文件。为此,我使用了两个 BackgroundWorkers :一个用于读取文件,它为我的文件的每个“行”生成一个可变大小的 List<byte>,另一个用于处理“行”。
由于我希望它们并行运行,而我不知道哪个会比另一个更快,所以我使用Queue 在两个BackgroundWorkers 之间传递数据。
事情是这样的:任何时候List<byte> 都不应该包含任何0 值。我检查之前将它们添加到队列中。尽管如此,在Queue 的另一端,一些列表包含0 值。然而,我在每次调用Dequeue() 时创建一个新的List<byte>,因为显然,如果我不这样做,数据会在处理完成之前被修改。
我尝试手动创建一个新的List<byte> 对象并然后为其分配Dequeue() 的结果,但没有改进。这是我第一次使用Queue,由于我的代码是多线程的,因此几乎不可能逐步调试。
Queue<List<byte>> q = new Queue<List<byte>>(); // My FIFO queue
// Reading thread
private void BackgroudWorkerRead_DoWork(object sender, DoWorkEventArgs e)
{
// ... read the file
List<byte> line_list = new List<byte>();
// ... filling line_list with data
// in this part I check that no byte added to line_list has the value 0, or else I display an errror message and end the process
q.Enqueue(line_list);
if (!backgroundWorkerNewLine.IsBusy) backgroundWorkerNewLine.RunWorkerAsync(); // if the other BackgroundWorker isn't processing data, now it needs to since we just added some to the queue
}
// Processing thread
private void backgroundWorkerNewLine_DoWork(object sender, DoWorkEventArgs e)
{
while (q.Count > 0) // While there is data to process
{
string line_str = DecodeBytes(new List<byte>(q.Dequeue())); // Decoding
string[] elements = line_str.Split(separator, StringSplitOptions.None); // Separating values
Form1.ActiveForm.Invoke(new MethodInvoker(() => AddRow(elements))); // Add the line to a DataTable from the main thread
}
}
public string DecodeBytes(List<byte> line)
{
/// ... read each byte and return a string of the whole decoded line
}
public void AddRow(string[] el)
{
MyDataTable.Rows.Add(el);
}
q.Dequeue() 返回的 List 似乎与 q.Enqueue() 添加的数据不同
【问题讨论】:
-
在两个不同的线程上同时读写会让你很痛苦。
标签: c# .net multithreading queue backgroundworker