Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait thread question

I have a UserControl with a tree on it. It uses multithreading to add nodes to it. I have a function called Expand which I need to execute after filtering completed and since I'm a newbie with multithreading I'm not sure how to do that. Here's my code:

class MyClass : UserControl
{
    private Thread nThread;
    private bool searchLoadCompleted = false;

    private void Filter()
    {
        ClearTree();
        this.nThread = new Thread(new ParameterizedThreadStart(AddFilteredResultsToTree));
        this.nThread.IsBackground = true;
        this.nThread.Start(someParameter);
    }

    private void AddFilteredResultsToTree(int someParameter)
    {
        myTree.Invoke(new MethodInvoker( ()=> this.searchLoadCompleted = false ));
        myTree.Invoke(new MethodInvoker( ()=> AppendNode(......) ));
        myTree.Invoke(new MethodInvoker( ()=> this.searchLoadCompleted = true ));
    }   

    private void Expand()
    {
    }
}

I tried to add nThread.Join() into Expand() but it got stuck indefinitely. What should I do?

like image 556
dstr Avatar asked Mar 16 '26 22:03

dstr


1 Answers

If the singlethreaded version of this is:

ClearTree();
AddFilteredResultsToTree(someparameter);
Expand();

Don't bother going multithreading, just do it on the same thread. The point of using multithreading there would be to let the main thread handle UI events, if you join the thread then you're basically just launching a background thread while freezing (not doing any work) in the main thread. Note that by calling Invoke you're actually delegating the execution of AddFilteredResultsToTree to the main thread anyway.

I'd suggest you simply call Expand from AddFilteredResult and use the Dispatcher to update the UI if needed or.

Another way to go (best in my opinion) would be to use the Async Pattern for this (example and tutorial here), and then on the AsyncCallback update the UI.

like image 76
Jorge Córdoba Avatar answered Mar 18 '26 12:03

Jorge Córdoba