[英]InvalidOperationException when using threading
I got InvalidOperationException in my Forms application. 我在Forms应用程序中收到InvalidOperationException。 I create new thread in button click event method:
我在按钮单击事件方法中创建新线程:
private void btn_Start_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(() =>
{
presenter.RunAlgorithm();
}));
thread.Start();
}
There is the code when I got exception: 当我得到异常时有代码:
public string Distance
{
get { return cbo_DistanceMeasure.SelectedValue.ToString(); }
}
This property get selected by user value of comboBox. 该属性由comboBox的用户值选择。 Then this value is used in presenter class in method RunAlgorithm().
然后,在方法RunAlgorithm()的演示者类中使用此值。 I read that for this kind of exception I must use Thread-Safe Calls to controls, like in this article: How to: Make Thread-Safe Calls to Windows Forms Controls .
我读到,对于这种异常,我必须对控件使用线程安全调用,如本文中所述: 如何:对Windows Forms Controls进行线程安全调用 。 But how use this in my scenario, when I used MVP pattern with Properties to set-get controls value ?
但是,当我将MVP模式与Properties一起使用来设置控件的值时,如何在我的场景中使用它呢? Is possible to use delegate with Properties, because I've got more properties which work with controls.
可以将委托与属性一起使用,因为我有更多可以与控件一起使用的属性。
The problem is you're trying to access control from a different thread - its not allowed. 问题是您正在尝试从其他线程访问控制-不允许这样做。 In Windows Forms you need to do this:
在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: 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?
}
You can also do directly from property if it can access Dispatcher 如果属性可以访问Dispatcher,则也可以直接从属性执行操作
public string Distance
{
get
{
return Dispatcher.Invoke(() => cbo_DistanceMeasure.SelectedValue.ToString(), DispatcherPriority.Background);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.