Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add object in treeview from another thread

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);
    }
}
like image 924
Ilia Avatar asked Feb 07 '23 10:02

Ilia


2 Answers

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.

like image 173
d.moncada Avatar answered Feb 15 '23 12:02

d.moncada


I think you need to do this:

Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => GetFiles(directory, tree)));
like image 20
SlashLP97 Avatar answered Feb 15 '23 14:02

SlashLP97