Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate objects in worker thread and bind to them
    primarykey
    data
    text
    <p>I've a problem with cross-thread operations in C# / WPF / .NET 4.0.</p> <p><strong>The situation:</strong></p> <p>I have to create a object tree when the user clicks a button and then bind to the tree. Because the creation takes a long time (child objects are recursively instantiated), I used a Thread/BackgroundWorker/Task to prevent the UI from freezing.</p> <p><strong>The problem:</strong></p> <p>I get a XamlParserException (Must create DependencySource on same Thread as the DependencyObject) when binding to the object tree.</p> <p>I understand the problem, but how can it be fixed? I can't create the object tree on the UI thread because this will freeze the UI. But I also can't create the object-tree on another thread because then I'm not able to bind to it.</p> <p>Is there a way to 'marshal' objects to the UI thread?</p> <p><strong>The Event Handler Code</strong> (executed on UI thread)</p> <pre><code> private void OnDiff(object sender, RoutedEventArgs e) { string path1 = this.Path1.Text; string path2 = this.Path2.Text; // Some simple UI updates. this.ProgressWindow.SetText(string.Format( "Comparing {0} with {1}...", path1, path2)); this.IsEnabled = false; this.ProgressWindow.Show(); this.ProgressWindow.Focus(); // The object tree to be created. Comparison comparison = null; Task.Factory.StartNew(() =&gt; { // May take a few seconds... comparison = new Comparison(path1, path2); }).ContinueWith(x =&gt; { // Again some simple UI updates. this.ProgressWindow.SetText("Updating user interface..."); this.DiffView.Items.Clear(); this.Output.Items.Clear(); foreach (Comparison diffItem in comparison.Items) { this.DiffView.Items.Add(diffItem); this.AddOutput(diffItem); } this.Output.Visibility = Visibility.Visible; this.IsEnabled = true; this.ProgressWindow.Hide(); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); } </code></pre> <p><strong>Example Binding</strong></p> <pre><code> &lt;DataGrid.Columns&gt; &lt;DataGridTemplateColumn CellTemplate="{StaticResource DataGridIconCellTemplate}"/&gt; &lt;DataGridTextColumn Header="Status" Binding="{Binding Path=ItemStatus}"/&gt; &lt;DataGridTextColumn Header="Type" Binding="{Binding Path=ItemType}"/&gt; &lt;DataGridTextColumn Header="Path" Binding="{Binding Path=RelativePath}" Width="*"/&gt; &lt;/DataGrid.Columns&gt; </code></pre> <p>Greetings, Dominik</p>
    singulars
    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.
 

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