Reputation: 131
I have a multithreading application which write to the same file on a specific event . how can i lock the file and make the thread wait until its free ? i can't use FileStream since it will throw exception on the other threads (can't acces)
FileStream fileStream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
is there any proper way to do this ?
Upvotes: 13
Views: 12030
Reputation: 13146
You need a thread-safe filewriter to manage threads. You can use ReaderWriterLockSlim
to perform it.
public class FileWriter
{
private static ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim();
public void WriteData(string dataWh,string filePath)
{
lock_.EnterWriteLock();
try
{
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] dataAsByteArray = new UTF8Encoding(true).GetBytes(dataWh);
fs.Write(dataAsByteArray, 0, dataWh.Length);
}
}
finally
{
lock_.ExitWriteLock();
}
}
}
Example;
Parallel.For(0, 100, new ParallelOptions { MaxDegreeOfParallelism = 10 },i =>
{
new FileWriter().WriteData("Sample Data", Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"SampleFile.txt"));
});
Upvotes: 14