gpt4 book ai didi

c# - Windows Forms .NET 中的 DataGridViewRow 线程安全

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:48 24 4
gpt4 key购买 nike

在我不断寻求更好地理解 .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;
}

最佳答案

根据 the documentation ,实例方法不是线程安全的。我不知道 DataGridViewRow 有任何有用的静态成员,所以我认为您应该使用 Invoke()。

更重要的是,您能否改变一些事情,让您的 UI 线程完成对 UI 的所有操作,而让其他线程进行后台处理?这是处理多线程的最佳方式。

关于c# - Windows Forms .NET 中的 DataGridViewRow 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24270651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com