Tuesday, September 3, 2013

Thread Locking

When sharing data between threads using static fields, chances are that the unique fields will be accessed/evaluated twice. Using an exclusive lock fixes this.

    class Program
    {
        static bool done;
        static readonly object locker = new object();

        static void Main(string[] args)
        {
            new Thread(Go).Start();
            Go();
        }

        static void Go()
        {
            lock (locker)
            {
                if (!done)
                {
                    Console.WriteLine("Completed."); //this must be accessed once
                    done = true;
                }
            }
            Console.ReadKey();
        }
    }

No comments:

Post a Comment