I have a wpf application.
During the running of the application, when I get to some method I fire event which performs some operations . In this event I have to access to an instance of DLL that works with Database , and it throws exception which tells that another thread owns that object. What would be the best way to handle this?
//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);
}
}
when I compare two strings in the if statement, It doesn’t throw an exception , but when I want to use DB_manager or to use the UI components , I get the –
The calling thread cannot access this object because a different thread owns it.
Should I pass to the event a connection string and make a new instance in the object? Or there is another , better solution?
thanks…
the best way to do it is to use the Dispatcher.Invoke method …
this.textBlock_theNextstring.Dispatcher.Invoke.
Sample –
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/360540eb-d756-4434-86f9-a3449f05eb55