Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating and passing complex content to the GUI thread in WPF/C#
    primarykey
    data
    text
    <p>I'm aware, and use, the xxx.Dispatcher.Invoke() method to get the background thread to manipulate GUI elements. I think I'm bumping up against something similar, but slightly different, where I want a long running background task to construct a tree of objects and when done hand it to the GUI for display.</p> <p>Attempting to do that results in an InvalidOperationException, "due to the calling thread cannot access this object because a different thread owns it." Curiously, this doesn't happen with simple type.</p> <p>Here's some example code that demonstrates a trivial case the throws the exception. Any idea how to work around this? I'm pretty sure that the problem is the background thread owns the factory constructed object and that the foreground GUI thread can't take ownership, although it works for more simple system types.</p> <pre><code>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) =&gt; { def = "DEF"; r = new Run("blah"); }; // When the background is done, use the factory objects with the GUI bgw.RunWorkerCompleted += (s2,e2) =&gt; { abc = abc + def; // WORKS: I suspect there's a new object Console.WriteLine(abc); // Console emits 'ABCDEF' List&lt;String&gt; l = new List&lt;String&gt;(); // 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(); } </code></pre> <p>The grand scope of the problem is that I have a large document that I'm constructing on the fly in the background and would love for the GUI to show what's been generated so far without having to wait for completion.</p> <p>How can a background worker act as an object factory and hand off content to the main thread?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload