2

In my continual quest to better understand thread-safe programming in .NET, I can't seem to get clarity on a question, so I'm hoping that someone on SO might be able to assist.

I understand that a Windows Form Control should not be accessed by a non-UI/worker thread directly without using Control.Invoke or Control.BeginInvoke. However, what about in the case of a DataGridViewRow object? If I understand correctly, the DataGridViewRow object itself is NOT a Control. However, it's normal usage is to add it to a DataGridView Control. Does this affect the way that we need to interact with the DataGridViewRow object?

For example, if you have a DataGridViewRow object added to a DataGridView Control, is it safe to access the DataGridViewRow object directly? Or is it the case that since it has been added to the DataGridView Control, it therefore must only be accessed by using DataGridView.Invoke.

Note, in this example we are not modifying the value and instead are only reading it. Does this even matter?

    //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;
    }
4

1 回答 1

2

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

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

于 2014-06-17T18:29:48.573 回答