gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:33:43 26 4
gpt4 key购买 nike

在线程方面,我是个新手,但在使用以下代码时,我得到了一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com