有很多关于这个的帖子,都围绕着一个共同的解决方案。我曾尝试使用此解决方案,但不相信它像我希望的那样可靠。如果有人可以指出我做错了什么或提出建议以使其更充分地证明,请发布!
情况:观看共享网络文件夹..如果网络丢失,filewatcher 会丢失它试图观看的内容并且服务终止。以下代码确实有效,但并非一直有效。该事件在尝试设置 FS 的路径属性时被触发。如果找不到路径(网络关闭),则会引发异常。我抓住了它,基本上睡了 x 次,然后再试一次。理想情况下,听起来它可以正常工作,但并不像看起来那么可靠:(
Protected Overrides Sub OnStart(ByVal args() As String)
fs1 = New FileSystemWatcher
fs1.Filter = My.Settings.MonitoringFilter
' fs1.NotifyFilter = NotifyFilters.LastWrite
fs1.Path = My.Settings.MonitoringDirNOSlash
' Add event handlers.
AddHandler fs1.Error, AddressOf WatcherError
fs1.EnableRaisingEvents = True
End Sub
Protected Sub WatcherError(source As Object, e As ErrorEventArgs)
fs1.Dispose()
fs1 = New FileSystemWatcher
Dim c As Integer = 0
While Not fs1.EnableRaisingEvents
Try
fs1.Filter = My.Settings.MonitoringFilter
fs1.Path = My.Settings.MonitoringDirNOSlash
AddHandler fs1.Error, AddressOf WatcherError
fs1.EnableRaisingEvents = True
Catch ex As Exception
c += 1
If c = 1 Then
ErrorReport(ex.Message)
End If
System.Threading.Thread.Sleep(5000)
End Try
End While
End Sub