简体   繁体   中英

'System.InvalidOperationException' occurred in System.Windows.Forms.dll in Task

I'm building a Winform application and i want to update a TreeView that represents a directory tree. This method takes one or two seconds, so i want to run it in parallel.

Firstly i use a Task.Factory.StartNew() with this code bellow, but i received the error 'System.InvalidOperationException' occurred in System.Windows.Forms.dll in Task .

Task loadTreeViewTask = Task.Factory.StartNew(() =>
        {
            try {
                directoryTreeView.Nodes.Clear();
                ....
                PopulateTreeView(directory, directoryTreeView.Nodes[0]);
            }
            catch (Exception e) {
               //Log
               //Change try/catch to CancellationToken
            }
        });

Then i saw that Windows works with a single thread UI, and i found that i need to use InvokeRequired:

directoryTreeView.Invoke((MethodInvoker)(() =>
{
  try {
    directoryTreeView.Nodes.Clear();
    ....
    PopulateTreeView(directory, directoryTreeView.Nodes[0]);
  }
  catch (Exception e) {
   //Log
   //Change try/catch to CancellationToken
  }
}));

There is a better way to do this?

The first portion of your code won't work because you are trying to update a control that was created on the UI thread, so, yes, you will need to use the Invoke method. You cannot update UI controls that were created on the UI thread from another thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM