要让FileSystemWatcher线程永远运行,可以采取以下措施:
while (true)
{
try
{
FileSystemWatcher watcher = new FileSystemWatcher();
// 配置FileSystemWatcher
watcher.EnableRaisingEvents = true;
// 等待事件发生
System.Threading.Thread.Sleep(Timeout.Infinite);
}
catch (Exception ex)
{
// 记录异常
Console.WriteLine("An error occurred: " + ex.Message);
// 等待一段时间后重新启动线程
System.Threading.Thread.Sleep(5000);
}
}
fsnotify
。package main
import (
"fmt"
"time"
"github.com/fsnotify/fsnotify"
)
func main() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("Error creating watcher:", err)
return
}
defer watcher.Close()
err = watcher.Add("/path/to/watch")
if err != nil {
fmt.Println("Error adding path:", err)
return
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
fmt.Println("Event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
fmt.Println("Modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("Error:", err)
}
}
}
以上两种方法都可以实现FileSystemWatcher线程的持续运行,可以根据具体情况选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云