使用线程时出现InvalidOperationException

时间:2014-03-18 17:45:15

标签: c# .net multithreading winforms

我的Forms应用程序中出现了InvalidOperationException。我在按钮点击事件方法中创建新线程:

private void btn_Start_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(new ThreadStart(() =>
    {
        presenter.RunAlgorithm();
    }));

    thread.Start();

}

当我遇到异常时有代码:

public string Distance
    {
        get { return cbo_DistanceMeasure.SelectedValue.ToString(); }
    }

此属性由comboBox的用户值选择。然后,此值在方法RunAlgorithm()中的presenter类中使用。我读到,对于这种异常,我必须使用线程安全调用来控制,如本文所述:How to: Make Thread-Safe Calls to Windows Forms Controls。但是在我的场景中如何使用它,当我使用MVP模式和属性设置获取控件值?可以将委托与属性一起使用,因为我有更多可以使用控件的属性。

1 个答案:

答案 0 :(得分:0)

问题是你是否试图从另一个线程访问控制 - 这是不允许的。在Windows窗体中,您需要执行此操作:

public string Distance
{
    get
    {
        if(this.InvokeRequired)
        {
            return (string)this.Invoke(new Func<string>(this.GetDistance));
        }

        return this.GetDistance();
    }
}

string GetDistance()
{
    return cbo_DistanceMeasure.SelectedValue.ToString();
}

WPF:

private void btn_Start_Click(object sender, EventArgs e)
{
    string selectedValue = Dispatcher.Invoke(() => cbo_DistanceMeasure.SelectedValue.ToString(), DispatcherPriority.Background);

    //Do something with the value here, maybe set your property value?
}

如果可以访问Dispatcher

,您也可以直接从属性进行操作
public string Distance
{
    get
    {
        return Dispatcher.Invoke(() => cbo_DistanceMeasure.SelectedValue.ToString(), DispatcherPriority.Background);
    }
}