我正在构建一个c#应用程序,它将单独的FilesystemWatcher实例监视多个文件夹并更新它的关联列表框。FilesystemWatcher只触发一次事件
public class MyFileWatcher
{
private TextBox _textBox;
private ListBox _listBox;
private string _folderDestination;
FileSystemWatcher _watcher;
public MyFileWatcher(TextBox textBox, ListBox listBox, string destfolderTextBox , System.ComponentModel.ISynchronizeInvoke syncObj)
{
this._textBox = textBox;
this._listBox = listBox;
this._folderDestination = destfolderTextBox;
this._watcher = new FileSystemWatcher();
// this._watcher.SynchronizingObject = syncObj;
this._watcher.Changed += new FileSystemEventHandler(convertXML);
this._watcher.IncludeSubdirectories = false;
this._watcher.Path = textBox.Text;
this._watcher.EnableRaisingEvents = true;
// add any other required initialization of the FileSystemWatcher here.
}
public void WatchFile(TextBox ctrlTB, ListBox ctrlLB)
{
// FileSystemWatcher _watcher = new FileSystemWatcher();
//var localTB = ctrlTB as TextBox;
//var localLB = ctrlLB as ListBox;
_watcher.Path = ctrlTB.Text;
_watcher.Path = ctrlTB.Text;
_watcher.NotifyFilter = NotifyFilters.LastWrite;
_watcher.Filter = "*.xml";
_watcher.Changed += new FileSystemEventHandler(convertXML);
// _watcher.Changed += (s, e) => convertXML(s,e);
// _watcher.Error += new ErrorEventHandler(WatcherError);
_watcher.EnableRaisingEvents = true;
_watcher.IncludeSubdirectories = false;
ctrlLB.Items.Add("Started Monitoring @ " + ctrlTB.Text);
ctrlLB.SelectedIndex = ctrlLB.Items.Count - 1;
}
这从被解雇:
public void button9_Click(object sender, EventArgs e)
{
if (!Directory.Exists(this.textBox1.Text))
{
//Form2.ActiveForm.Text = "Please select Source Folder";
// popup.Show("Please Select Source Folder");
MessageBox.Show("Please Select Proper Source Folder");
return;
}
else
{
textBox1.Enabled = false;
button9.Enabled = false;
button1.Enabled = false;
// button4.Enabled = false;
// FileSystemWatcher _watcher = new FileSystemWatcher();
// _watcher.SynchronizingObject = this;
// WatchFile(textBox1,listBox1 ,_watcher);
//object syncobj = Form1.ActiveForm;
string destfolder = textBox7.Text + "\\";
destfolder += "test.xml";
MyFileWatcher myWatcher = new MyFileWatcher(textBox1, listBox1, destfolder, this);
myWatcher.WatchFile(textBox1, listBox1);
}
}
现在,当这个被解雇。它第一次运作,但第二次没有回升。我觉得像实例正在垃圾回收。但我不明白的是它在MyFileWatcher类中声明为全局。
您正在'button9_Click'中创建一个局部变量'myWatcher'(所以,'MyFileWatcher'可能会被垃圾回收,是的。)。如果将“MyFileWatcher”添加为字段,会发生什么情况? – Default 2014-09-25 06:45:47
[FileSystemWatcher可能重复 - 只有一次触发的更改事件?](http://stackoverflow.com/questions/1313942/filesystemwatcher-only-the-change-event-once-firing-once) – Reniuz 2014-09-25 06:45:54
但是'myWatcher'是一个可以收集的局部变量。它没有实现'IDisposable'(它应该),但是最终'FileSystemWatcher'也会被收集。 – Dirk 2014-09-25 06:46:07