I have a multithreading app, and I need to add object from another thread to the treeview. But I keep getting an exception
Action being performed on this control is being called from the wrong thread. Marshal to the correct thread using Control.Invoke or Control.BeginInvoke to perform this action.
Here is my code
ThreadPool.QueueUserWorkItem(new WaitCallback(GetFiles), entryPoint);
private void GetFiles(object entryPoint)
{
var localData = entryPoint as EntryPoint;
this.GetFiles(localData.DirectoryInfo, localData.TreeNode);
localData.ManualEvent.Set();
}
private void GetFiles(DirectoryInfo directory, TreeNode tree)
{
for (int i = 0; i < allFiles.GetLength(0); i++)
{
tree.Nodes.Add(allFiles[i].Name);
}
}
As the error states, you need to perform UI related actions on the UI thread. In order to do this, you can use BeginInvoke
from the control itself.
private void GetFiles(DirectoryInfo directory, TreeNode tree)
{
if (TreeViewControl.InvokeRequired)
{
TreeViewControl.BeginInvoke((MethodInvoker)delegate
{
for (int i = 0; i < allFiles.GetLength(0); i++)
{
tree.Nodes.Add(allFiles[i].Name);
}
});
}
}
You can find more information here.
I think you need to do this:
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => GetFiles(directory, tree)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With