Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# multiple threads writing to the same file

Tags:

c#

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 ?

like image 533
Vic Avatar asked Dec 02 '17 14:12

Vic


1 Answers

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"));
});
like image 127
lucky Avatar answered Sep 19 '22 08:09

lucky