加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 线程池:跨线程操作无效.

发布时间:2020-12-15 17:22:45 所属栏目:百科 来源:网络整理
导读:当涉及到线程时我很新,但是在使用以下代码时我得到一个InvalidOperationException.我知道它正在尝试访问importFileGridView,但这是由创建异常的UI线程创建的.我的问题是,我该如何解决这个问题? GetAllImports可以有一个返回类型吗?如何从UI线程访问临时文
当涉及到线程时我很新,但是在使用以下代码时我得到一个InvalidOperationException.我知道它正在尝试访问importFileGridView,但这是由创建异常的UI线程创建的.我的问题是,我该如何解决这个问题? GetAllImports可以有一个返回类型吗?如何从UI线程访问临时文件?

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.Invoke或Control.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",MessageBoxIcon.Information);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读