【问题标题】:DataGridViewRow thread safety in Windows Forms .NETWindows Forms .NET 中的 DataGridViewRow 线程安全
【发布时间】:2014-08-07 20:52:08
【问题描述】:

在我不断寻求更好地理解 .NET 中的线程安全编程的过程中,我似乎无法弄清楚一个问题,所以我希望 SO 上的某个人能够提供帮助。

我了解在不使用 Control.Invoke 或 Control.BeginInvoke 的情况下,非 UI/工作线程不应直接访问 Windows 窗体控件。但是,在 DataGridViewRow 对象的情况下呢?如果我理解正确,DataGridViewRow 对象本身不是控件。但是,通常的用法是将其添加到 DataGridView 控件中。这会影响我们需要与 DataGridViewRow 对象交互的方式吗?

例如,如果您将 DataGridViewRow 对象添加到 DataGridView 控件,直接访问 DataGridViewRow 对象是否安全?还是因为它已被添加到 DataGridView 控件中,因此只能通过使用 DataGridView.Invoke 来访问它。

注意,在这个例子中,我们没有修改值,而只是读取它。这还重要吗?

    //since we are passing a DataGridViewRow object and NOT the actual DataGridView Control object, is it safe to call this method directly from a worker thread?  Note, in this code example we are NOT modifying the value and instead we are only reading it.  If were WERE modifying the value, would it make a difference?
    string retrieveColumn1Value (DataGridViewRow row)
    {
        string column1String = row.Cells[column1].Value.ToString(); 
        return column1String;
    }

    //or is it the case that since the DataGridViewRow object has been added to our DataGridView Control, that we have to use this method instead to ensure thread-safety?
    string retrieveColumn1ValueWithInvoke (DataGridViewRow row)
    {
        string column1String = (string)dataGridView1.Invoke(new retrieveColumnValuesDelegate(lookupColumnValues), new object[] { row });
        return column1String;
    }

【问题讨论】:

    标签: c# .net multithreading winforms datagridviewrow


    【解决方案1】:

    根据the documentation,实例方法不是线程安全的。我不知道 DataGridViewRow 有什么有用的静态成员,所以我想说你应该使用 Invoke()。

    更重要的是,你能改变一些事情,让你的 UI 线程处理 UI 的所有操作,而将其他线程留给后台处理吗?这是处理多线程的最佳方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-16
      • 2011-02-28
      • 1970-01-01
      • 2011-08-02
      • 2013-06-10
      • 2010-09-28
      • 2011-11-04
      • 2011-11-06
      相关资源
      最近更新 更多