Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Does anyone have a simple way of making this TreeView WinForm app multithreaded – the UI locks up. I have experimented with the backgroundworker , treeview.invoke and delegates but need help in these areas. Thank you in advance for any assistance.
Posted
Updated 20-Oct-13 14:36pm
v5
Comments
Sergey Alexandrovich Kryukov 19-Oct-13 1:41am    
Of course you can use threads, and it's not so hard, and of course you need to use Control.Invoke or Dispatcher.
But what's the problem?

Your code does nothing with threads, so my question is: http://whathaveyoutried.com?
No, the code you show does not count... :-)

—SA

1 solution

Doing the Threading stuff is pretty easy - a Background worker will handle that:
C#
    BackgroundWorker work = new BackgroundWorker();
    work.DoWork += new DoWorkEventHandler(work_DoWork);
    work.ProgressChanged += new ProgressChangedEventHandler(work_ProgressChanged);
    work.WorkerReportsProgress = true;
    work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerCompleted);
    work.RunWorkerAsync(files);
    ...

void work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    butSync.Enabled = true;
    }

void work_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    string mess = e.UserState as string;//string.Format("{0}/{1}: {2}", e.ProgressPercentage, files.Length, files[e.ProgressPercentage]);
    Console.WriteLine(mess);
    }

void work_DoWork(object sender, DoWorkEventArgs e)
    {
    BackgroundWorker work = sender as BackgroundWorker;
    // Do background loop here.
    }
The complication comes when you are adding the actual TreeNodes, because the background worker can't access UI components (such as the TreeView) directly without causing a cross threading exception. You could use Invoke to move that code onto your main thread, but then you are throwing events around like a loon in an application such as this.

The method I used last time I did this was to create the folders as a list in the background worker and then use the Worker.ReportProgess to pass the list and the node to which it applies back up to the UI thread for it to add - because each event does a limited set of work it doesn't impact the UI so badly and the user gets a sensible update each time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900