我试图创建一个监控页面来监控运行的各种文件系统观察程序。我需要知道的是如何让多个文件系统观察者访问UI线程中的列表框..这是一些代码:
private void WatchFile(TextBox ctrlTB,ListBox ctrlLB,FileSystemWatcher _watcher)
{
// 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 convertXML(object source, FileSystemEventArgs f)
{
/// some job
}
我需要将每个filesystemwatcher的状态回发回它的相应列表框。我点击开始按钮即可宣告FSW。每个列表框都有一个开始按钮,它将单独声明。例如:
private 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);
}
}
线程如何知道要访问哪个控制列表框。非常感谢回复。
答案 0 :(得分:1)
Encapsulate您的WatchFile
和convertXml
就像这样
public class MyFileWatcher {
private TextBox _textBox;
private ListBox _listBox;
FileSystemWatcher _watcher;
public MyFileWatcher(TextBox textBox, ListBox listBox, ISynchronizeInvoke syncObj) {
this._textBox = textBox;
this._listBox = listBox;
this._watcher = new FileSystemWatcher();
this._watcher.SynchronizingObject = syncObj;
this._watcher.Path = textBox.Text;
this._watcher.Changed += new FileSystemEventHandler(convertXML);
this._watcher.EnableRaisingEvents = true;
this._watcher.IncludeSubdirectories = false;
// add any other required initialization of the FileSystemWatcher here.
}
protected virtual void convertXML(object source, FileSystemEventArgs f) {
// interact with this._textBox and this._listBox here as required.
// e.g.
// this._listBox.Items.Add(f.FullPath);
}
}
这样您就可以将FileSystemWatcher实例绑定到特定的TextBox和ListBox,或者您想要的任何其他对象。
然后替换您的button9_Click
方法:
private 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;
// instantiate your new instance of your MyFileWatcher class.
MyFileWatcher myWatcher = new MyFileWatcher(textBox1,listBox1 ,this);
}
}
注意:我实际上没有编译或执行此代码,因此可能存在例外情况。但整体模式应该能够解决你所追求的问题。