ディレクトリの変更をリッスンしていて、それが使用できなくなった場合 (サーバーの再起動など)、FileSystemWatcher は例外をスローします。これは、リッスンできるOnError イベントを提供し、問題の処理方法を決定できます。
複数のウォッチャーを実行するアプリケーションがあり、1 つのエラーが発生すると、アプリケーションは 30 秒ごとにループして再度接続を試みてエラーを処理します。また、接続に失敗し、最終的に (約 1 時間後に) 接続をあきらめた回数の現在までの合計を保持します。
VB.Net の一般的な考え方は次のとおりです。
''' <summary>
''' This event is called when an error occurs with the file watcher. Most likely the directory being watched is no longer available (probably from a server reboot.)
''' </summary>
Protected Sub Scan_Error(ByVal Source As FileSystemWatcher, ByVal E As ErrorEventArgs)
'// Stop listening
Source.EnableRaisingEvents = False
'// Maximum attempts before shutting down (one hour)
Dim Max_Attempts As Integer = 120
Dim Timeout As Integer = 30000
Dim I As Integer = 0
'// Attempt to listen - if fail, wait and try again in 30 seconds.
While Source.EnableRaisingEvents = False And I < Max_Attempts
I += 1
Try
Source.EnableRaisingEvents = True
Catch
Source.EnableRaisingEvents = False
System.Threading.Thread.Sleep(Timeout)
End Try
End While
End Sub