我有一個wpf應用程序。 在應用程序運行期間,當我遇到某種方法時,我會觸發執行一些操作的事件。在這個事件中,我必須訪問一個與Database一起工作的DLL實例,並且它會拋出異常,它告訴另一個線程擁有該對象。處理這個問題的最佳方法是什麼?嘗試從另一個線程,wpf,c訪問對象時出現跨線程異常#
//this is in the main thread - in MainWindow.cs - code behind
MyDataBaseManager DB_manager = new MyDataBaseManager(connectionString);
//event handler
void MainWindow_MyCustomEvent(object sender, MainWindow.MyCustomEventArgs e)
{
try
{
if (str1 == str2)
{
//getting exception when trying to perform this statement
DB_manager.UpdateTable(this.textBlock_MyTextBlock.Text, DateTime.Now, currenrUser);
theNextstring = DB_manager.GetTheNextString();
if (theNextstring != string.Empty)
{
this.textBlock_theNextstring.Text = theNextstringף
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OKCancel, MessageBoxImage.Error);
}
}
當我在if語句比較兩個字符串,它不拋出一個異常,但是當我想用DB_manager或使用UI組件,我得到的 -
The calling thread cannot access this object because a different thread owns it.
我應該傳遞給事件一個連接字符串並在對象中創建一個新實例嗎?或者還有另一個更好的解決方案?
感謝...
問題*不會*在任的'if'語句,如果他們只是比較字符串變量。問題將出現在你如何提取字符串開始。 –
據我的理解,我認爲你不應該直接在主線程上調用/執行數據庫操作,因爲它在你的應用程序範圍之外,並且你不想阻塞用戶線程。可以在你的模型中使用一個命令模式,併爲你的視圖模型引發相應的編組事件,它應該更新你的視圖。只是一個建議。 – whoisthis