写入Excel会遗漏一些使用线程的数据

我使用Kinect v2来logging和计算一个主题的骨架,这是一个耗时的任务。 我也同时写入关于骨架的数据到一个Excel工作表,冻结软件。 因此,我使用Thread来处理Excel写作任务。 它运行顺利,但问题是,当我写一个Excel工作表,它错过了一些单元格,如图所示。 任何build议?

在这里输入图像说明

testThreadStart11 = new ThreadStart(excelwriter); testThread11 = new Thread(testThreadStart11) { IsBackground = true }; testThread11.Start(); public void excelwriter() { _excelWorksheet.Cells[_excelCol, 1] = _excelRowNum; _excelWorksheet.Cells[_excelCol, 2] = limb1.ToString(); _excelWorksheet.Cells[_excelCol, 3] = limb2.ToString(); _excelCol++; _excelRowNum++; } 

在主线程中将所有值存储到队列中,并且只在一个后台线程中将值从此队列写入到excel中

示例代码:

  class Data { public int C1 { get; set; } public int C2 { get; set; } public int C3 { get; set; } } class Program { static Queue<Data> RowsDataQueue = new Queue<Data>(); static void Main(string[] args) { ThreadStart testThreadStart11 = new ThreadStart(excelwriter); Thread testThread11 = new Thread(testThreadStart11) { IsBackground = true }; testThread11.Start(); while (true) { Data RowData = ReadDataFromSomeWhere(); RowsDataQueue.Enqueue(RowData); } } public static void excelwriter() { while (true) { if (RowsDataQueue.Count > 0) { Data D = RowsDataQueue.Dequeue(); //write values in the D to the excel file... } } } private static Data ReadDataFromSomeWhere() { throw new NotImplementedException(); } } 

你的代码看起来像你每行开始一个线程,并保持你的类的状态。

没有正确的线程同步,这将不起作用。 其他线程将在运行时修改_excelCol和_excelRowNum。 如果你只是需要这个卸载UI线程,考虑只是开始一个新的线程。 或者在修改状态周围添加正确的locking