FileStream.Lock, FileStream.Unlock and its sync.

J

John

I've got multiple threads and processes that write to same
file. Before writing all threads / processes first lock
part of file and then write to file. If one thread /
process locks file, another threads / processes can not
lock this file again. And I want that all threads /
processes wait until first thread frees lock by calling
FileStream.Unlock. But I do not know what code should I
use that all threads / processes wait until first thread /
process unlock file.


My code :

FileStream FS = new FileStream
("\\Logs\\CriticalError.log",FileMode.Append,FileAccess.Wri
te,FileShare.ReadWrite);
BinaryWriter BW = new BinaryWriter(FS);

try {FS.Lock(0,10);}
catch (IOException E) { // This exception is thrown if
file is already locked
// Here I want that my thread waits until file is unlocked
and then I can lock file successfully.
}

....

FS.Unlock(0,10);
FS.Close();

What sync function should I use that my thread should
waited until file is unlocked ?

Can you give me short sample.

Thank you very much.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top