【问题标题】:Writing to Excel misses some data using Thread使用 Thread 写入 Excel 会丢失一些数据
【发布时间】:2015-12-20 20:50:31
【问题描述】:

我正在使用 Kinect v2 记录对象的骨骼并对其进行一些计算,这是一项耗时的任务。我还将有关骨架的数据同时写入 Excel 表,这会冻结软件。因此,我使用 Thread 来处理 Excel 编写任务。它运行顺利,但问题是当我写入 Excel 工作表时,它会丢失一些单元格,如图所示。有什么建议吗?

 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++;
 }

【问题讨论】:

    标签: c# excel multithreading kinect


    【解决方案1】:

    在主线程中将所有值存储到一个队列中,并在一个后台线程中将该队列中的值写入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();
            }
        }
    

    【讨论】:

      【解决方案2】:

      您的代码看起来像是每行启动一个线程,并在您的类中保持状态。

      如果没有正确的线程同步,那将无法工作。其他线程将在运行时修改 _excelCol 和 _excelRowNum。如果您只需要它来卸载 UI 线程,请考虑只启动一个新线程。或者在修改状态周围添加适当的锁定。

      【讨论】:

      • 我只想卸载你提到的 UI。你能告诉我我应该改变什么吗?
      • 鉴于您的代码非常小,很难准确地说出。但是,概括地说,如果您有 testThread.Start 在循环内,请将其移出循环。你只想要一个线程。如果不确定,请尝试在线程 Start(); 处设置断点;打电话。
      猜你喜欢
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多