Windows Forms . net中的DataGridViewRow线程安全性

本文关键字:线程 安全性 DataGridViewRow 中的 Forms net Windows | 更新日期: 2023-09-27 18:08:57

在我不断寻求更好地理解。net线程安全编程的过程中,我似乎无法明确一个问题,因此我希望so上的某人可能能够提供帮助。

我明白Windows窗体控件不应该由非ui/工作线程直接访问,而不使用控件。调用或Control.BeginInvoke。然而,在DataGridViewRow对象的情况下呢?如果我理解正确,DataGridViewRow对象本身不是一个控件。然而,它的正常用法是将它添加到datagridviewcontrol。这是否会影响我们需要与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;
    }

Windows Forms . net中的DataGridViewRow线程安全性

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

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