Thread and retry writing file

In my application I am using Threads to write data to BinaryStream files.

It occasionally happens that two threads are trying to write to the same file and then an IoException occurs.
Unfortunately there is no option to lock the files.

What I want to do is retry writing the data to the file inside the same Thread until it succeeds.

Recalling the method from the thread itself is crashing the thread.

So how can I do this?

Thank you.

Andre.

Simple example to clarify what I mean:

[code]Sub myThread

Dim f As FolderItem = New FolderItem(filepath,FolderItem.PathTypeShell)
Dim stream As BinaryStream

If f <> Nil Then
if NOT f.Exists Then
stream = BinaryStream.Create(f, true)
else
stream = BinaryStream.open(f, true)
end if
stream.Position = partSizeBegin -1
stream.Write(data)
stream.Close
End If

Exception e as IOException
Call myThread <-- this crashes the thread

End Sub[/code]

Use a Semaphore around the file access in each thread.

Excellent solution.
Thanks Tim.

Not so excellent solution after all, because I forgot to mention that the files are accessed by several different console applications.
The Semaphore works only from inside the same app.

As far as I know a Mutex completely blocks an app from starting when another app is already running. So this may also not be a solution.

Any other ideas?

Use ipcsocket from every console app to another console app that’s the only to write the file?

No, that’s not what a Mutex does (although it can be used to implement that). It’s just a system-wide way to restrict access to something. It would certainly work to provide a system-wide way to restrict access to a file that is used by several different apps.

Okay, Mutex worked !!

Thanks guys.