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 ?
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"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With