C # how to implement a class that works with controls and enable the thread?

advertisements

I have written a class that fills a treeview for me. IN my project I need this treeview several times and I don;t want to copy paste my code, so I decided to create a class that fills the treeview for me.

On some forms I want to use a thread to fill the treeview. This is because sometimes it can take some time to load the data and fill the treeview.

In my treeview-class I pass the treeview in the constructor. At the moment I want to fill the treeview, I call the LoadTreeview() method.

I'd like to call the LoadTreeview method on a thread, but when I do this I get the exception that the treeview is created on another thread. Which is logic off course. But I was wondering, what is the best way to create a custom class that works with controls and you want to use this class in a thread?

Do I need to write this code on every 'GUI-action'?

treeview.Invoke((MethodInvoker)delegate
{
  treeview.Nodes.Add(MyNode);
})

Or are there other (smarter) ways?


Both your and Levisaxos' solutions will prevent the crash but you should really benchmark the runtime performance of this. The problem is that if you insert lots of nodes to the treeview and each node is inserted through Control.Invoke your code will not be doing much but synchronizing to the UI thread. If this is the case you should consider to separate loading the data that is needed to create the nodes for the treeview from the actual insertion of the nodes. Instead load the data asynchronously and then synchronously insert all nodes at once.