c# - 线程池 : Cross-thread operation not valid.

标签 c# .net multithreading threadpool

在线程方面,我是个新手,但在使用以下代码时,我得到了一个 InvalidOperationException。我知道它正在尝试访问 importFileGridView 但这是由创建异常的 UI 线程创建的。我的问题是,我该如何解决这个问题? GetAllImports 是否可能有返回类型?如何从我的 UI 线程访问 temp

ThreadPool.QueueUserWorkItem(new WaitCallback(GetAllImports), null);

private void GetAllImports(object x)
    {
        DataSet temp = EngineBllUtility.GetAllImportFiles(connectionString);
        if (temp != null)
            importFileGridView.DataSource = temp.Tables[0];
        else
            MessageBox.Show("There were no results. Please try a different search", "Unsuccessful", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

最佳答案

您不能在后台线程上更改用户界面组件。在这种情况下,必须在 UI 线程上设置 DataSource。

您可以通过 Control.InvokeControl.BeginInvoke 处理它,如下所示:

private void GetAllImports(object x)
{
    DataSet temp = EngineBllUtility.GetAllImportFiles(connectionString);
    if (temp != null)
    {
        // Use Control.Invoke to push this onto the UI thread
        importFileGridView.Invoke((Action) 
            () => 
            {
                importFileGridView.DataSource = temp.Tables[0];
            });
    }
    else
        MessageBox.Show("There were no results. Please try a different search", "Unsuccessful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

关于c# - 线程池 : Cross-thread operation not valid.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8670086/

相关文章:

C# 向量类 - 插值设计决策

c# - 将逗号分隔的参数传递给 SQL 中的存储过程

C# + SQLite - 数据库锁

multithreading - 使用 runspacepools 导入联系人

java - Hotspot JIT 编译器完成的任何指令重新排序是否可以重现?

c# - 找出集合中的差异

c# - 在 Linq 中动态选择列和聚合函数

.net - SQL Azure 使用哪种 ORM?

c# - 在 C# 上登录用户后注销

.net - 从 .NET 访问另一个盒子上的 COM 对象(不推荐使用 DCOM,远程处理)