简体   繁体   English

C#Treeview线程安全操作

[英]C# treeview threadsafe operations

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 谢谢

From the MSDN documentation on System.Windows.Forms.TreeView : System.Windows.Forms.TreeView上MSDN文档中

Any public static ( Shared in Visual Basic) members of this type are thread safe. 此类型的任何公共static (在Visual Basic中为Shared )成员都是线程安全的。 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: 幸运的是,Windows窗体中有一种机制可以以线程安全的方式处理来自多个线程的控件:

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. 这将确保操纵树的代码将在创建TreeView的线程中执行,因此它将是线程安全的。 If you don't want to inherit from TreeView, you can just use treeInstance.InvokeRequired and treeInstance.Invoke( ). 如果不想从TreeView继承,则可以只使用treeInstance.InvokeRequiredtreeInstance.Invoke( )。

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 我总是通过这种方法通过将一些信息传递给GUI对象来批准它的...我从没想过将函数的整个主体放在其中

Thanks 谢谢

Brad 布拉德

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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