监听文件变化,并且在主线程呈现结果

来源:互联网 发布:jumpsoles 淘宝 编辑:程序博客网 时间:2024/06/05 20:35
//声明传递FileSystemEventArgs对象的委托private delegate void setLogTextDelegate(FileSystemEventArgs e);//创建监听private void button1_Click(object sender, EventArgs e){label1.Text = "正在监听中……";FileSystemWatcher watch = new FileSystemWatcher();watch.Path = @"f:\";watch.Filter = "a.css";watch.NotifyFilter = NotifyFilters.LastWrite;watch.Changed+=new FileSystemEventHandler(watch_Changed);watch.EnableRaisingEvents = true;}//监听到变化后的事件,跨线程private void watch_Changed(object source, FileSystemEventArgs e){//判断是否跨线程if (this.InvokeRequired){//使用委托将方法封送到UI主线程处理this.Invoke(new setLogTextDelegate(showMain), new object[] { e });}}//主线程UIprivate void showMain(FileSystemEventArgs e){this.label1.Text = e.FullPath;}

注意:文件更新后watch_Changed事件会被触发两次。最简单的解决方法就是接受到事件后,立刻关闭监听。处理结束后,重新启动监听。
原创粉丝点击