This is a mirror of official site: http://jasper-net.blogspot.com/

Synchronizing Threads in Multithreaded application in .Net - C#

| Tuesday, July 26, 2011
The Problem "Concurrency"

When you build multithreaded application, your program needs to ensure that shared data should be protected from against the possibility of multiple threads engagement with its value. What's going to happen if multiple threads were accessing the data at the same point? CLR can suspend your any thread for a while who's going to update the value or is in the middle of updating the value and same time a thread comes to read that value which is not completely updated, that thread is reading an uncompleted/unstable data.

To illustrate the problem of concurrency let write some line of code

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("----Synchronnization of Threads-----");
        Console.WriteLine("Main Thread {0}", Thread.CurrentThread.ManagedThreadId);
        Printer p = new Printer();

        Thread[] threads = new Thread[5];

        //Queue 5 threads
        for (int i = 0; i < 5; i++)
        {
            threads[i] = new Thread(new ThreadStart(p.PrintNumbersNonSync));
        }
        foreach (Thread t in threads)
        {
            t.Start();
        }

        Console.ReadLine();
    }
}

class Printer
{
    public void PrintNumbersNonSync()
    {
        Console.WriteLine(" ");
        Console.WriteLine("Executing Thread {0}", Thread.CurrentThread.ManagedThreadId);
        for (int i = 1; i <= 10; i++)
        {
            Console.Write(i + " ");
        }
    }
}


Read more: C# Corner
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://www.c-sharpcorner.com/UploadFile/vendettamit/8486/

Posted via email from Jasper-net

0 comments: