【问题标题】:Control 'dataGridView1' accessed from a thread other than the thread it was created on控件“dataGridView1”从创建它的线程以外的线程访问
【发布时间】:2014-09-19 16:19:19
【问题描述】:

我有一个 windows 窗体,它需要永远将数据加载到我的 datagridview 中。

所以我以为我使用了一个线程,但我不断收到错误:

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

这是我的代码:

private void Form1_Load(object sender, EventArgs e)
    {
       //lblFormDisplayStatus.Text = "Retrieving Data from Database";

        if (isProcessRunning)
        {
            MessageBox.Show("A process is already running.");
            return;
        }

        SetIndeterminate(true);

        Thread backgroundThread = new Thread(
            new ThreadStart(() =>
            {
                isProcessRunning = true;

                Thread.Sleep(5000);

                //MessageBox.Show("Thread completed!");                    

                BeginInvoke(new Action(() => Close()));

               RunProgram(); // the method responsible for binding the data to datagrid         

                isProcessRunning = false;
            }
        ));
        backgroundThread.Start();

        ShowDialog();           

    }

请让我摆脱痛苦,告诉我哪里出错了

谢谢

【问题讨论】:

  • pls put me out of my misery and show me where I am going wrong - 你可能有兴趣观看this short clip
  • 这很有帮助... :p

标签: c# multithreading


【解决方案1】:

UI 控件与线程无关(需要在创建控件的线程上更新)。 在您的情况下,您正在运行一个新线程,该线程正在调用一个似乎正在更新 UI 控件 (dataGridView1) 的方法。

作为快速参考:阅读 Control.BeginInvoke (MSDN)。

另外,这个问题和你的类似: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

编辑:更新 DataGridView 的方法/语句需要在 UI 线程上运行。像这样的:

private void  RunProgram()
{
  //Do time consuming work here (non-UI thread)
   dataGridView1.BeginInvoke(new InvokeDelegate(AttachData));
}
private void AttachData()
{
   //dataGridView1.Table.... Bind data here (this method would be executed on UI thread)
}

【讨论】:

  • 在 formLoad 上,我用进度条显示表单,以便用户知道正在发生的事情并等待。我只需要知道在哪里放置我的方法???
  • 明白了!!!我所做的只是从上述方法中删除 Close())) 并将其替换为 RunProgram() 并且它可以工作.....
  • 如果我的回答帮助您到达那里,您可以接受它,这会将您的问题标记为已回答。这将帮助其他有类似问题的人。
  • 谢谢您....说实话我根本没有使用您的建议,我只是如上所述更改了我的代码的一部分,因此您的建议可能会使某人感到困惑...对不起
猜你喜欢
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 2016-05-21
  • 2016-06-11
  • 2015-05-14
相关资源
最近更新 更多