Baran Topal

Baran Topal


October 2024
M T W T F S S
« Feb    
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories


Create 12 thread that try to write data into C:\MyFile.txt in a syncronized fashion in C#

baranbaran

Here is another gem that I found in my backups 🙂

Below program will create 12 thread that try to write data into C:\MyFile.txt in a syncronized fashion in C#.


using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;

namespace ThreadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
        }
    }

    class MyClass
    {
        const string myFilePath = @"C:\MyFile.txt";
        object myLockControl = new object();
        Random rnd = new Random();

        public MyClass()
        {
            // Start 12 threads that write over the same file.
            for (int i = 0; i < 12; i++)
            {
                System.Threading.Thread th = new Thread(new ThreadStart(WriteFileData));
                th.Start();
            }
        }

        void WriteFileData()
        {
            while (true)
            {
                lock (myLockControl)// If you comment/remove this line you will see random errors like "The process cannot access the file 'C:\MyFile.txt' because it is being used by another process."
                {
                    int thId = System.Threading.Thread.CurrentThread.ManagedThreadId;
                    string text = thId + " - " + DateTime.Now.ToString() ;
                    Console.WriteLine(text);
                    System.IO.File.AppendAllText(myFilePath, text + Environment.NewLine);
                }
                System.Threading.Thread.Sleep(rnd.Next(50, 500));
            }
        }
    }
}

Basically when a thread go into the scope of the lock, all the other need to wait until the current thread exit the lock scope, then another thread go inside the lock block and so on.

Be aware that if your file is writing by different process then the way to do this is diferent, the lock keyword only work for the threads inside a process, in this case you must use another aproach like implement the System.Threading.Mutex class.