如何从另一个线程在Treeview中添加对象 [英] How to add object in treeview from another thread

查看:166
本文介绍了如何从另一个线程在Treeview中添加对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程应用程序,我需要将另一个线程中的对象添加到树视图中.但我不断遇到异常

I have a multithreading app, and I need to add object from another thread to the treeview. But I keep getting an exception

正在从错误的线程调用对此控件执行的操作.使用Control.Invoke或Control.BeginInvoke将其编组到正确的线程以执行此操作.

Action being performed on this control is being called from the wrong thread. Marshal to the correct thread using Control.Invoke or Control.BeginInvoke to perform this action.

这是我的代码

ThreadPool.QueueUserWorkItem(new WaitCallback(GetFiles), entryPoint);

private void GetFiles(object entryPoint) 
{ 
      var localData = entryPoint as EntryPoint; 
      this.GetFiles(localData.DirectoryInfo, localData.TreeNode); 
      localData.ManualEvent.Set(); 
}

private void GetFiles(DirectoryInfo directory, TreeNode tree) 
{ 
    for (int i = 0; i < allFiles.GetLength(0); i++) 
    { 
        tree.Nodes.Add(allFiles[i].Name);
    }
}

推荐答案

由于错误状态,您需要在UI线程上执行与UI相关的操作.为此,您可以在控件本身中使用BeginInvoke.

As the error states, you need to perform UI related actions on the UI thread. In order to do this, you can use BeginInvoke from the control itself.

private void GetFiles(DirectoryInfo directory, TreeNode tree) 
{ 
    if (TreeViewControl.InvokeRequired)
    {
        TreeViewControl.BeginInvoke((MethodInvoker)delegate
        {
            for (int i = 0; i < allFiles.GetLength(0); i++) 
            { 
                tree.Nodes.Add(allFiles[i].Name);
            }
        });
    }
}

您可以在此处.

这篇关于如何从另一个线程在Treeview中添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆