private void Form1_Load(object sender, EventArgs e)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = ConfigurationManager.AppSettings["fromPath"]; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt"; // Add event handlers.
watcher.Created += new FileSystemEventHandler(OnCreated); // Begin watching.
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
MessageBox.Show(e.FullPath + e.ChangeType + "创建 ");
this.label1.Text = e.FullPath + e.ChangeType + "创建 ";
}
上面的代码运行时会发生错误:线程间操作无效: 从不是创建控件“label1”的线程访问它。
线程的知识了解的不多,能帮忙从线程的角度讲解下上面代码的执行过程吗,感激不尽。
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = ConfigurationManager.AppSettings["fromPath"]; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt"; // Add event handlers.
watcher.Created += new FileSystemEventHandler(OnCreated); // Begin watching.
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
MessageBox.Show(e.FullPath + e.ChangeType + "创建 ");
this.label1.Text = e.FullPath + e.ChangeType + "创建 ";
}
上面的代码运行时会发生错误:线程间操作无效: 从不是创建控件“label1”的线程访问它。
线程的知识了解的不多,能帮忙从线程的角度讲解下上面代码的执行过程吗,感激不尽。
=>
this.Invoke(_=>{label1.Text = e.FullPath + e.ChangeType + "创建 "});
{
MessageBox.Show(e.FullPath + e.ChangeType + "创建 ");
this.label1.Text = e.FullPath + e.ChangeType + "创建 ";
}
上面的事件是在另一个线程中执行的,而label1是在主线程创建的,C#的规定为只有创建控件的线程才能访问控件,所以上面的事件不能直接访问label1,需要使用委托的方式。
http://hi.baidu.com/zzticzh/blog/item/ee4e89020a89a6094bfb518e.html
watcher.EnableRaisingEvents = true;
------------------
开启了一个新的线程用于检测文件夹的变化
private void OnCreated(object source, FileSystemEventArgs e)
{
MessageBox.Show(e.FullPath + e.ChangeType + "创建 ");
this.label1.Text = e.FullPath + e.ChangeType + "创建 ";
}
--------------------------
在新的线程中修改主线程创建的控件 因为是在主线程中创建的,所以抱错.