I have tried this in VB.2010 and 2019. This is a Windows Desktop app.
It has a FileSystemWatcher create routine that gets control when a file is put into a folder and then processes the file via an invoked function. The invoked function must be synchronous and will have unpredictable problems if multiple instances invoked.
The issue is that once the function (DoMonitorFolder) is invoked the lock is lost and the synclock block will be entered again before the first block completes.
Simplified code is below. With breakpoints I have seen that:
- The block is entered before the End Synclock is reached the 2nd time if multiple files are put into the folder. BreakPoints were put after the SyncLock and on the End SyncLock
- The RunningFileNowBol is true when entered the 2nd time. It which is set to true in DoFolderMonitor when entered and false before it returns.
- If DoFolderMonitor is taken out the Synclock block is only entered after the End Synclock is executed which is what I expected.
So is the a restriction about embedding a function call within the block? Is there an alternative that will synchronize the calling of DoFolderMonitor from FSW.Created?
Private Sub FSW_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FSW.Created
SyncLock TheProgram ' & "FWS_CREATED"
If RunningFileNowBol Then
iNop = iNop
Else
If Not DoFolderMonitor(pFFn:=e.FullPath) Then
GoTo ExitFunction
End If
End If
End SyncLock
ExitFunction:
Return
End Sub
It seems that System.Windows.Forms.Application.DoEvents() breaks the SyncLock. When DoEvents was not executed then it worked as expected. I am not sure about MuteX but after about 10 hours of trial and error I am done for now.
If anyone has a good alternative that does not break the lock unless released I would appreciated it if you let me know.