我有一个WPF应用程序。
在应用程序运行期间,当我使用某种方法时,会触发执行一些操作的事件。在这种情况下,我必须访问与Database一起使用的DLL实例,并且它引发异常,该异常表明另一个线程拥有该对象。处理此问题的最佳方法是什么?
//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.
我应该向事件传递一个连接字符串并在该对象中创建一个新实例吗?还是有另一个更好的解决方案?
谢谢...
最佳答案
最好的方法是使用Dispatcher.Invoke方法...
this.textBlock_theNextstring.Dispatcher.Invoke。
样本 -
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/360540eb-d756-4434-86f9-a3449f05eb55
关于wpf - 尝试从另一个线程(wpf,C#)访问对象时发生跨线程异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10630583/