当涉及到线程时我很新,但是在使用以下代码时我得到一个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.@R_473_4045@ion); }
解决方法
您无法在后台线程上更改用户界面组件.在这种情况下,必须在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.@R_473_4045@ion); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。