I have an application that creates a new thread every second. Each thread is passed the address of a method in an instance of a class. The method polls a directory for files. The method then checks for a trigger file (filename.not) for each file. If the file does not have a trigger file, no processing is done on it. So, when the thread finds the trigger file, it deletes it, so no other thread will try to process it.
Here's the code:
Private Sub TimerTick(ByVal sender As Object, ByVal e As System.EventArgs)
transmission = New TransmissionThread()
Dim t As New Threading.Thread(AddressOf transmission.MainProcess)
Public Sub MainProcess()
For Each sFile In IO.Directory.GetFiles(reg.PGCDirectory, "*.file")
Dim fi As New IO.FileInfo(sFile)
If IO.File.Exists(sFile & ".not") Then
' Here the error occurs, when more than one thread executes the following:
IO.File.Delete(sFile & ".not")
Shell("c:\program files\winzip\WZZIP.EXE " & sTarget & sChunkName & " -a " & sFile, AppWinStyle.Hide, True, 5000)
bChunkCreated = True
IO.File.Move(sFile, sTarget & fi.Name)
My problem lies in the fact that there are instances when two or more threads are trying to delete the trigger file at the same time (which happens when you are working with 800+ files).
I've tried setting the attribute to read-only and then having the thread check the attribute before trying to access it....however, I then run into the problem of two or more threads trying to write the attribute, or the attribute is not changed quick enough for the other thread to recognize it.
How do I communicate to the thread that a file is already being accessed by another thread?