当涉及到线程时我很新,但是在使用以下代码时我得到一个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", "Unsuccessful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}