0

可能重复:
跨线程操作无效:控件从创建它的线程以外的线程访问

我在尝试使用 BackgroundWorker 时遇到问题。

我有一个复选框,单击时我想调用 BackgroundWorkers RunWorkerAsync 方法:

    private void checkBoxLoadRecords_CheckedChanged(object sender, EventArgs e)
    {
        bw.RunWorkerAsync();
    }

因此,在 DoWork 事件中,我在其中一个组合上调用了 SelectionChangeComitted 事件:

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        comboSelectedIDs_SelectionChangeCommitted(sender, e);
    }

在 SelectionChangeComitted 方法中,我在尝试将 ID 检索到变量中的第一行收到错误。我收到的错误是:跨线程操作无效:控件'comboSelectedIDs'从创建它的线程以外的线程访问。

void comboSelectedIDs_SelectionChangeCommitted(object sender, EventArgs e)
{
    int idToUse = (int)multiSelectedIDs.SelectedValue; //Errors here!
    SetupNamesCombo(idToUse);
}

我该如何解决这个问题?

我想在使用我的自定义控件时我会遇到类似的问题,因为它们使用组合文本值,我想在 BackgroundWorker 中得到它。

我正在使用 C# 4.0

提前致谢。

4

2 回答 2

0

Use the Dispatcher class to access to the UI elements from different threads:

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            int idToUse = (int)multiSelectedIDs.SelectedValue;
        });

Or if you are in a code behind file you can just do this without the Deployment.Current.

于 2012-08-13T13:15:03.127 回答
0

You cannot access UI controls in any thread other than the UI thread.

One solution is to save the values of the UI controls in a separate POCO object, so you can access them from the background worker.

于 2012-08-13T13:15:29.460 回答