c# - Using FileSystemWatcher to delete Childnode from TreeView, getting "Cross-thread operation not valid" error -
a filesystemwatcher set update treeview reflect files in directory on disk. fires expected , search through treeview returns correct node, when issue nodetodelete.remove() command, following error:
an unhandled exception of type 'system.invalidoperationexception' occurred in system.windows.forms.dll
additional information: cross-thread operation not valid: control '_tvwfiles' accessed thread other thread created on.
i didn't realize using more 1 thread. suggestions on how remedy this? or perhaps different way gain access child node remove it?
the code follows:
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(); } } }
any thoughts appreciated. thank you!
as remember (i may mistaken , can't check right now) filesystemwatcher uses threadpool internally. maybe that's why getting exception.
try setting
_watcher.synchronizingobject = this;
Comments
Post a Comment