Question

I am looking for information on using a treeview in safethread manner. Does any one have experance with this or know of some online links to research.

Thanks

Was it helpful?

Solution

From the MSDN documentation on System.Windows.Forms.TreeView:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Fortunately for you, there is a mechanism in Windows Forms to handle controls from multiple threads in a thread safe way:

public delegate void TreeActionDelegate(WhatToDo details);

public void DoSomethingWithThisTree(WhatToDo details)
{
    // Assuming that 'this' points to a TreeView
    if (this.InvokeRequired) this.Invoke(new TreeActionDelegate(),
        new object[] { details });
    else
    {
        // The body of your function
    }
}

Now you can invoke this function from any thread:

DoSomethingWithThisTree(new WhatToDo("something"));

This will guarantee that the code that manipulates your tree will be executed in the thread that created the TreeView, hence it will be thread-safe. If you don't want to inherit from TreeView, you can just use treeInstance.InvokeRequired and treeInstance.Invoke().

OTHER TIPS

Thanks...

the line "//the body of your function" gave me a kick start.

I have allways approched this with just passing some information to GUI object by this method...I never thought to place the whole body of the function in there

Thanks

Brad

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top