I know and use the xxx.Dispatcher.Invoke () method to get a background thread for managing GUI elements. I think I come across something similar, but a little different, where I need a long background task to create a tree of objects and when we pass it to the GUI for display.
Attempting to do this throws an InvalidOperationException, "because of the calling thread, it is not possible to access this object because it has a different thread." Curiously, this does not happen with a simple type.
Here is an example code that demonstrates a trivial case that throws an exception. Any idea how to get around this? I am sure that the problem is that the background thread owns the created factory object and that the front-end GUI thread cannot take responsibility, although it works for simpler types of systems.
private void button1_Click(object sender, RoutedEventArgs e)
{
String abc = "ABC";
Paragraph p = new Paragraph();
BackgroundWorker bgw = new BackgroundWorker();
String def = null;
Run r = null;
bgw.DoWork += (s1,e2) =>
{
def = "DEF";
r = new Run("blah");
};
bgw.RunWorkerCompleted += (s2,e2) =>
{
abc = abc + def;
Console.WriteLine(abc);
List<String> l = new List<String>();
l.Add(def);
p.Inlines.Add(r);
};
bgw.RunWorkerAsync();
}
The big problem is that I have a large document that I create on the fly in the background, and I would like the GUI to display what has been created so far without waiting for completion.
How can a background worker act as a factory object and transfer content to the main thread?
Thank!