我建立了一个c#应用程序,它将拥有单独的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);
}
}
现在被解雇了。它第一次工作,但它第二次没有。我觉得 _watcher 实例正在被垃圾收集。但我不明白的是它在 MyFileWatcher 类中声明为全局。
答案 0 :(得分:2)
MyFileWatcher myWatcher = new MyFileWatcher(textBox1, listBox1, destfolder, this);
由于这是一个局部变量,而MyFileWatcher
拥有FileSystemWatcher
,因此它将被垃圾收集起来。
如果您例如将myWatcher
添加为字段,它应该可以正常工作。