使用FileSystemWatchers共享同一个事件处理程序是否安全?使用具有不同目录的多个FileSystemWatchers使用相同的事件处理程序是否安全?
我们需要将FileSystemWatcher包装在以下类中,以使事件处理程序线程安全吗?
Class Snippets
Private _watchPaths As New List(Of String) From {"x:\Dir1", "x:\Dir2"}
Private _watchers As List(Of FileSystemWatcher)
Private _newFiles As New BlockingCollection(Of String)
Sub Watch()
Dim _watchPaths As New List(Of String) From {"x:\Dir1", "x:\Dir2"}
Dim watchers As List(Of FileSystemWatcher)
For Each path In _watchPaths
Dim watcher As New FileSystemWatcher
AddHandler watcher.Created, Sub(s, e)
_trace.DebugFormat("New file {0}", e.FullPath)
'Do a little more stuff
_newFiles.Add(e.FullPath)
End Sub
Next
End Sub
End Class
我们需要将FileSystemWatcher包装在以下类中,以使事件处理程序线程安全吗?
Class FileWatcher
Private _fileSystemWatcher As New FileSystemWatcher
Public Sub Start(path As String, filter As String, action As Action(Of Object, FileSystemEventArgs))
With _fileSystemWatcher
.Path = path
.Filter = filter
.EnableRaisingEvents = True
AddHandler .Created, Sub(s, e)
action(s, e)
End Sub
End With
End Sub
Public Sub [Stop]()
_fileSystemWatcher.Dispose()
End Sub
End Class
这里是助手类的使用方法:
Sub Watch
For Each path In _watchPaths
Dim Watcher as new FileWatcher
watcher.Start(path, "*.txt"), Sub(s, e)
_trace.DebugFormat("New file {0}", e.FullPath)
'Do a little more stuff
_newFiles.Add(e.FullPath)
End Sub)
Next
End Sub
BlockingCollection
对象,则您是线程安全的。 如果您添加了其他内容,则必须使用类似于 SyncLock 的东西。 - Peter Ritchie