使用FileSystemWatcher从TreeView中删除Childnode,使“跨线程操作无效”错误

时间:2015-04-29 03:51:56

标签: c# .net multithreading treeview children

设置FileSystemWatcher以更新TreeView以反映磁盘上目录中的文件。它按预期触发,通过TreeView搜索返回正确的节点,但是当我发出nodeToDelete.Remove()命令时,我收到以下错误:

System.Windows.Forms.dll中出现未处理的“System.InvalidOperationException”类型异常

附加信息:跨线程操作无效:控制从创建它的线程以外的线程访问的'_tvwFiles'。

我没有意识到我使用了多个线程。有关如何解决这个问题的任何建议?或者可能采用不同的方式来访问子节点以将其删除?

代码如下:

using System;
using System.IO;
using System.Windows.Forms;

namespace WaveManager
{
    public partial class FileViewControl : UserControl
    {
        public FileViewControl()
        {
            InitializeComponent();
        }

        private FileSystemWatcher _watcher;
        private const string path = @"c:\temp";

        public void OnWaveOpen(string fileName)
        {
        string filePath = Path.GetDirectoryName(fileName);

        TreeNode folderNode;
        _tvwFiles.ImageIndex = 0;
        _tvwFiles.SelectedImageIndex = 0;
        DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
        //folderNode = new TreeNode(directoryInfo.Name);
        folderNode = new TreeNode(filePath);
        folderNode.Tag = directoryInfo;

        //Getfiles
        TreeNode waveNode;

        foreach (FileInfo wavefile in directoryInfo.GetFiles("*.wav"))
        {
            waveNode = new TreeNode(wavefile.Name, 1, 1);
            waveNode.Name = waveNode.Text;
            waveNode.Tag = wavefile;
            folderNode.Nodes.Add(waveNode);
            }
            _tvwFiles.Nodes.Add(folderNode);

            _tvwFiles.ExpandAll();
        }

        private void OnLoad(object sender, System.EventArgs e)
        {
            if (DesignMode)
                return;
            _tvwFiles.ExpandAll();              
            _watcher = new FileSystemWatcher(path);
            _watcher.EnableRaisingEvents = true;
            _watcher.Deleted += OnFileDeleted;

        }

        private TreeNode FindNodeByTagText(String s, TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Tag.ToString() == s)
                    return node;

                TreeNode n = FindNodeByTagText(s, node.Nodes);
                if (n != null)
                    return n;
            }

            return null;
        }

        void OnFileDeleted(object sender, FileSystemEventArgs e)
        {
            string fn = Path.GetFileName(e.FullPath);
            TreeNode nodeToDelete = FindNodeByTagText(fn, _tvwFiles.Nodes);
            nodeToDelete.Remove();
        }
    }
}

任何想法都将不胜感激。谢谢!

0 个答案:

没有答案