跨线程操作无效:从创建它的线程以外的线程访问控件“dataGridView1”。

5

我是一名有用的助手,可以为您翻译以下内容。涉及到IT技术,需要翻译的内容如下:

我有一个Windows表单,加载数据到我的datagridview非常缓慢。

我一直在这一行代码中遇到错误:

    dataGridView1.Rows.Add(row);

跨线程操作无效:从非创建它的线程访问控件“dataGridView1”。以下是我的代码:
    public List<string> _checked = new List<string>();

    private void getBarcodProperty()
    {                
        string query = "select Name from RfidUnic where Barcode = @barcode";

        while (true)
        {
            while (_checked.Count > 0)
            {
                SQLiteCommand cmd = new SQLiteCommand(query, sqliteConnection);
                cmd.Parameters.AddWithValue("@barcode", _checked[0]);
                sqliteConnection.Open();

                SQLiteDataReader da = cmd.ExecuteReader();

                if (da.Read())
                {
                    if (!da.IsDBNull(0))
                    {
                        string[] row = new string[] { da[0].ToString(), "1", _checked[0] };
                        dataGridView1.Rows.Add(row);
                        _checked.RemoveAt(0);
                    }
                }
                else
                {
                    string[] row = new string[] { "empty", "1", _checked[0] };
                    dataGridView1.Rows.Add(row);
                    _checked.RemoveAt(0);
                }

                sqliteConnection.Close();
            }
        }
    }

请告诉我我的错误在哪里

谢谢

2个回答

16

你的“getBarcodProperty”函数是从另一个线程而不是UI线程中调用的,而你尝试在该方法中访问datagridview,因此会创建问题。

有两种方法可以解决这个问题。

  1. 在你的load方法 "RFID_Load(object sender, EventArgs e)" 中添加这行作为第一行。(在这种情况下,您无需更改任何代码)

Control.CheckForIllegalCrossThreadCalls = false;

更多细节 : http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html

  1. 另一个解决方案是使用委托。

dataGridView1.Invoke(new Action(() => { dataGridView1.Rows.Add(row); }));

注意:每次调用都必须执行相同的操作。


1
@alihomayouni 不建议使用Control.CheckForIllegalCrossThreadCalls = false;。请查看在调试期间,将 CheckForIllegalCrossThreadCalls 设为 false 来避免跨线程错误是否安全? - LarsTech

8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接