在我不断寻求更好地理解.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;
}
答案 0 :(得分:2)
根据the documentation,实例方法不是线程安全的。我不知道DataGridViewRow有任何有用的静态成员,所以我想你应该使用Invoke()。
更重要的是,您是否可以更改内容以便UI线程对UI进行所有操作,并将其他线程留给后台处理?这是处理多线程的最佳方式。