我有一个 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.
我应该将连接字符串传递给事件并在对象中创建一个新实例吗?还是有另一种更好的解决方案?
谢谢...