views:

487

answers:

2

Hello, 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

+4  A: 

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().

DrJokepu
A: 

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

Brad
Yes the beauty of this approach that the function will invoke itself, just in an other thread and if you invoked it from the same thread initially, it will not do any invoke at all. Unfortunately it wasn't me who came up with this, this method is actually suggested somewhere in the MSDN Library :)
DrJokepu