线程安全性数据网格视图 [英] Thread Safety & DataGridView

查看:93
本文介绍了线程安全性数据网格视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用BackgroundWorker和DataGridView的应用程序(WinForms,C#)中具有以下内容.

对于小型数据集,效果很好,但是在有大量行时会爆炸.绑定源错误,DataMember和DataSource不能相同,等等.他们不是.这是一个线程问题.

I have the following in an app (WinForms, C#) using a BackgroundWorker and a DataGridView.

Works fine for small datasets, but blows up when there are a boatload of rows. Binding source error, DataMember and DataSource can''t be the same, blah blah blah. Which they''re not. It''s a threading issue.

private void bkTrashCollection_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
  {
    BadFiles = 0;
    CollectTrash();
  }

private void CollectTrash()
  {
    foreach (DataGridViewRow Row in tbl_MediaDataGridView.Rows)
    {
      string FilePath = Row.Cells[3].Value.ToString();

      if (!File.Exists(FilePath))
      {
        MissingFiles.Add(FilePath);
        Row.DefaultCellStyle.BackColor = Color.Yellow;
        BadFiles += 1;
      }
  }
}



我应该在哪里放置锁"或调用"之类的东西,以便它可以工作?除了使BackColor的更改根本不发生,而不是至少有一半的工作时间之外,我没有发现任何可用的示例. :sigh:

我认为一种解决方法是使用"MissingFiles"列表从后台线程中出来时进行颜色更改,但如果可能的话,我宁愿一口气做一下.



Where do I put the Lock or Invoke or whatever so it will work? None of the examples I''ve found work, except to make the changing of the BackColor not happen at all, rather than at least working half the time. :sigh:

I think a workaround would be to use that "MissingFiles" list to do the color changes when it comes out of the background thread, but I''d rather do it all in one swell foop, if possible.

Is it possible?

推荐答案

您正在从工作线程访问控件,这是非法的.如果在调试器中运行此命令,则会引发异常以警告您.

将调用File.Exists放在单独的线程中是一个好主意,但是您必须获取文件路径并在UI线程上设置背景.

您还存在一个问题,即线程运行时网格中的数据可能会更改.

一种解决方案是在UI线程上创建文件路径的集合,并将其传递给您的BackgroundWorker.然后在完成的处理程序(在UI线程中运行)中再次搜索网格并设置背景以查找丢失的文件.

您必须在一排排的船"上测试其性能:)

尼克
You''re accessing the control from a worker thread, which is illegal. If you run this in the debugger, an exception will be thrown to warn you.

Putting the call to File.Exists in a separate thread is a good idea, but you must get the file paths and set the backgrounds on the UI thread.

You also have the problem that the data in the grid might change while your thread runs.

A solution would be to create a collection of file paths on the UI thread and pass that to your BackgroundWorker. Then in your completed handler ( which runs on the UI thread ) search the grid again and set the background for missing files.

You''ll have to test this for performance on "a boatload of rows" :)

Nick


这篇关于线程安全性数据网格视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆