在线程方面,我是个新手,但在使用以下代码时,我得到了一个 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.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);
}
关于c# - 线程池 : Cross-thread operation not valid.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8670086/