0

I'm trying to access the header properties of a TreeView control in a background worker's DoWork method.

I have tried the following:

var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerAsync(MyTreeView);

private void DoWork(object sender, DoWorkEventArgs e)
{
    var x = (e.Argument as TreeView);
    var item1 = x.Items[0] as TreeViewItem;

    //error here..
    var headerItem1 = item1.Header;
}

The error that is thrown says that the property I want to access is owned by another thread (the UI thread in my case).

I have had this problem only with the TreeView control so far. Passing and then accessing less 'complex' controls like Labels or TextBlocks has worked fine.

Thanks for every answer.

Szabolcs Dézsi
  • 8,743
  • 21
  • 29
yooloobooy
  • 493
  • 6
  • 12
  • It is possible that you are dealing with more data in a TreeView than you were with a Label or TextBlock control. Possible duplicate of [https://stackoverflow.com/q/9732709/6026377](https://stackoverflow.com/q/9732709/6026377) –  Oct 17 '17 at 20:47

1 Answers1

0

The rule is: only access the GUI elements (controls) on the GUI thread.

In a BackgroundWorker, the DoWork event handler will be called on a background thread. You are not allowed to access the GUI elements on that thread. Accessing means reading or writing properties (or indexers) or calling methods.

If you need to do something with a control on a background thread, use Dispatcher.Invoke method. But be warned, that using the Invoke/BeginInvoke methods might impact the overall performance (e.g. when used in a tight loop).

You have to redesign your logic in such a manner that you don't need to access the GUI elements on a background thread. This would be the best solution.

By the way, I would recommend you to move from the BackgroundWorker to the modern asynchronous patterns (async/await & Tasks).

dymanoid
  • 14,771
  • 4
  • 36
  • 64