[英]InvalidOperationException when using threading
我在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()的演示者類中使用此值。 我讀到,對於這種異常,我必須對控件使用線程安全調用,如本文中所述: 如何:對Windows Forms Controls進行線程安全調用 。 但是,當我將MVP模式與Properties一起使用來設置控件的值時,如何在我的場景中使用它呢? 可以將委托與屬性一起使用,因為我有更多可以與控件一起使用的屬性。
問題是您正在嘗試從其他線程訪問控制-不允許這樣做。 在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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.