在treenode.Nodes.Add(tn1)这一句上为什么抛出错误说:在该控件上执行的操作正从错误的线程调用。使用 Control.Invoke 或 Control.BeginInvoke 封送到正确的线程才能执行此操作
public partial class Form1 : Form
    {
        public delegate void MyDelegate(DirectoryInfo info, TreeNode treenode);
        public MyDelegate MD;
        public Form1()
        {
            InitializeComponent();
        }        private void Form1_Load(object sender, EventArgs e)
        {
            
            DirectoryInfo dinfo = new DirectoryInfo(@"C:\program files");
            TreeNode tn = new TreeNode();            MD = new MyDelegate(PrintRecursive);
            MD.BeginInvoke(dinfo, tn, null, null);
            treeView1.Nodes.Add(tn);
        }        protected void PrintRecursive(DirectoryInfo info,TreeNode treenode)
        {
            TreeNode tn1 = new TreeNode(info.Name);
            treenode.Nodes.Add(tn1);
            DirectoryInfo[] dinfo2 = info.GetDirectories();
            
            foreach (DirectoryInfo tn in dinfo2)
            {
                PrintRecursive(tn,tn1);
            }
        } 
    }

解决方案 »

  1.   

    做一下invokeable判断然后再调用窗体。
      

  2.   

    还是不行啊,一样的错误,我加了个invokeRequired判断
      

  3.   

      if (this.lblInfo.InvokeRequired)
                {
                    this.lblInfo.Invoke(new SetFileInfomationHande(SetFileInfomation), new object[] { message });
                }
      

  4.   

     else
                {
                    this.lblInfo.Text = message;
                }
      

  5.   

    BeginInvoke是后台线程,所以无法跨线程操作控件。。需要用委托来操作
      

  6.   

    请问下你这个lblinfo和SetFileInfomationHande是什么东西,我是新手。。不太懂
      

  7.   

    我改用成INVOKE了,不会出错,但好像不是单独线程来做了,有什么办法可以既用单独线程,又可以调用控件?
      

  8.   

    先定义个委托
    delegate void FormShow();
            FormShow _FormShow;
    并事例化
    _FormShow=new FormShow(ThisShow);
    private void ThisShow()
            {
                this.Show();
                if (_Dat.Save)
                {
                    SaveDat(Application.StartupPath + "\\MyDat.sd");
                }
                f2.Close();
                t.Abort();
            }
    线程中操作控件很麻烦必须用Invoke方法传递委托
    this.Invoke(_FormShow);
      

  9.   

    因为treenode是属于主线程的,而你的invoke是不能对主线程的控件直接操作的,其实你那个委托是多余的,只要将treenode.nodes.add做成委托就行了。