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

时间:2011-12-29 16:00:30

标签: c# .net multithreading threadpool

在涉及线程时我很新,但在使用以下代码时我得到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);
    }

2 个答案:

答案 0 :(得分:2)

您无法在后台线程上更改用户界面组件。在这种情况下,必须在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);
}

答案 1 :(得分:0)

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

您正在创建一个委托函数,该函数将作为参数通过调用它的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]);

我建议使用MethodInvoker而不是Action,请参阅:here

相关问题