Multithreading with Monitor for thread Synchronization and writing to a file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;

namespace Memory_understanding
{
    class writer
    {
        //private static Mutex mutex = new Mutex();

        public void writer_method(string inputline)
        {
            Monitor.Enter(this);
            using (StreamWriter str = new StreamWriter("sharedfile.txt",true))
            {
               
                str.WriteLine(inputline);
                str.Close();
                Console.WriteLine("Finished");
                Thread.Sleep(8000);
                Monitor.Exit(this);
            }

        }

    }

    class ThreadWriter
    {
        public static void Main()
        {

            writer wri = new writer();
            Thread t1 = new Thread(() => wri.writer_method("I will be writing from Thread1"));
            t1.Start();

            Thread t2 = new Thread(() => wri.writer_method("I will be writing from Thread2"));
            t2.Start();

            Thread t3 = new Thread(() => wri.writer_method("I will be writing from Thread3"));
            t3.Start();
            Console.ReadLine();
        }
    }
}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6