跨线程与具有数据源(ComboBox)的Control一起工作

Cross-thread work with Control which have a data source (ComboBox)

首先我会post代码,它很短而且很清楚。 cb_currentProfile 是一个组合框,在加载表单时填充了 3 个项目:

delegate void SetCurrentProfileCallback(int index);

private void SetCurrentProfile(int index) // Set index of Combobox.SelectedItem
{
    if (this.cb_currentProfile.InvokeRequired)
    {
        SetCurrentProfileCallback d = new SetCurrentProfileCallback(SetCurrentProfile);
        this.Invoke(d, new object[] { index });
    }
    else
    {
        this.cb_currentProfile.SelectedItem = 2;            // Won't work
        this.cb_currentProfile.Visible = false;             // It works
    }
}

问题是,当我尝试更改 SelectedItem 属性 时,它不会执行任何操作(没有崩溃,只是没有任何反应)。

我确定在我的表单申请中已达到此代码。

现在我正在 .NET 4.6 中制作它(但它在 v4.5 中也不起作用)

我调用这个方法的地方在Task body:

Task.Run(() =>
{
    while(true)
    {
        // ...
        SetCurrentProfile(2);
        // ...
        Thread.Sleep(100);
    }
});

我认为这个问题与 DataSource 有关,它似乎被主 UI 之外的其他线程不可见。

我也确信在代码到达任务创建之前,数据已加载到 ComboBox。

编辑 1 - 所选项目为空,计数 属性 returns 0

当我使用调试器检查一些数据时,结果是:

var x = this.cb_currentProfile.SelectedItem; // null
var y = this.cb_currentProfile.Items.Count;  // 0

看起来,使用 this.cb_currentProfile.SelectedItem = 2 语句,您打算通过 index 设置对 ComboBox 的选择。 ComboBox.SelectedItem Property accepts an Object and attempts to find it in its collection of items, selecting it if successful, and doing nothing otherwise. To select a particular index of the ComboBox, set the ComboBox.SelectedIndex Property 代替。