I was recently testing with some FileSystemWatchers and wonder how the event handling works in .NET. For example, with this code in VB.NET:
Dim fsw1, fsw2, fsw3 As New FileSystemWatcher()
Private Sub fsw_Error(sender As Object, e As ErrorEventArgs) _
Handles fsw1.Error, fsw2.Error, fsw3.Error
Dim iCont As Integer = 1
Dim fsw As FileSystemWatcher = CType(sender, FileSystemWatcher)
While Not fsw.EnableRaisingEvents AndAlso iCont < 120
iCont += 1
Try
fsw.EnableRaisingEvents = True
txtResultado.Clear()
Catch
fsw.EnableRaisingEvents = False
Threading.Thread.Sleep(30000)
End Try
End While
End Sub
Each time an error occurs on any of the FileSystemWatchers the function is executed. A different thread for the function is generated for each FileSystemWatcher? Can they interfere with each other while executing more than one at the same time?
There is maybe a difference between C# and VB.NET in this?
There are no constraints for which thread calls an event; if you feel like calling an event in another thread, you are free to do so in .NET. To be honest I cannot imagine implementing a FileSystemWatcher without using a separate thread or async IO for the watcher (which calls the event if a change is found), because you don’t want the events to interrupt the normal flow of the application.
Events in .NET work with an invocation list which is called when the event is raised. When invoking an event, the invocation list is walked and each method is called, in a single thread. Simple as that.
The functionality is .NET functionality so the same for both C# and VB.Net