繁体   English   中英

线程池:跨线程操作无效。

[英]Thread Pooling: Cross-thread operation not valid.

关于线程,我是一个新手,但是在使用以下代码时却遇到了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线程上完成数据源的设置。

您可以通过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);
}

芦苇说了什么,但我更喜欢这种语法:

发生的是您正在创建一个委托函数,该函数将通过调用它的Control.Invoke作为参数传递给UI线程,这样UI线程importFileGridView进行更改。

importFileGridView.Invoke((MethodInvoker) delegate {
                             importFileGridView.DataSource = temp.Tables[0];
                         });

您也可以这样写:

//create a delegate with the function signature
public delegate void SetDateSourceForGridViewDelegate (GridView gridView, Object dataSource);

//write a function that will change the ui
public void SetDataSourceForGridView(GridView gridView, Object dataSource)
{
    gridView.DataSource = dataSource;
}

//Create a variable that will hold the function
SetDateSourceForGridViewDelegate delegateToInvoke = SetDataSourceForGridView;

//tell the ui to invoke the method stored in the value with the given paramters.
importFileGridView.Invoke(delegateToInvoke, importFileGridView, temp.Tables[0]);

并且我建议使用ActionMethodInvoker参见: 此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM