在WPF/C中生成复杂内容并将其传递给GUI线程#

Wal*_*ner 3 c# wpf dispatcher invalidoperationexception backgroundworker

我知道并使用xxx.Dispatcher.Invoke()方法来获取后台线程来操作GUI元素.我想我正在碰到类似的东西,但略有不同,我想要一个长时间运行的后台任务来构建一个对象树,并在完成时将其交给GUI进行显示.

尝试这样做会导致InvalidOperationException,"由于调用线程无法访问此对象,因为其他线程拥有它." 奇怪的是,简单类型不会发生这种情况.

下面是一些示例代码,演示抛出异常的简单案例.知道如何解决这个问题吗?我很确定问题是后台线程拥有工厂构造的对象,并且前台GUI线程不能取得所有权,尽管它适用于更简单的系统类型.

private void button1_Click(object sender, RoutedEventArgs e) 
{  
   // These two objects are created on the GUI thread
   String abc = "ABC";  
   Paragraph p = new Paragraph();

   BackgroundWorker bgw = new BackgroundWorker();

   // These two variables are place holders to give scoping access
   String def = null;
   Run r = null;

   // Initialize the place holders with objects created on the background thread
   bgw.DoWork += (s1,e2) =>
     {
       def = "DEF";
       r = new Run("blah");
     };

   // When the background is done, use the factory objects with the GUI
   bgw.RunWorkerCompleted += (s2,e2) =>
     {
        abc = abc + def;         // WORKS: I suspect there's a new object
        Console.WriteLine(abc);  // Console emits 'ABCDEF'

        List<String> l = new List<String>();  // How about stuffing it in a container?
        l.Add(def);                           // WORKS: l has a reference to def

        // BUT THIS FAILS.
        p.Inlines.Add(r);  // Calling thread cannot access this object
     };

   bgw.RunWorkerAsync();
}
Run Code Online (Sandbox Code Playgroud)

问题的主要范围是我有一个大文档,我正在后台实时构建,并希望GUI显示到目前为止生成的内容,而不必等待完成.

后台工作者如何充当对象工厂并将内容传递给主线程?

谢谢!

Fra*_*nov 5

您正在尝试Run在后台线程中创建,但它Run是一个FrameworkContentElement继承自DispatcherObject并因此绑定到创建它的线程的线程.