Thread safe collection in .Net

In .NET 4.0 concurrent collection is available in System.Collections.Concurrent namespace.

Collections in the .NET Framework lower than 4.0 are not thread-safe by default and need to be locked for each operation.

We can make collection thread safe using lock and SyncRoot Property.

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

That means if you are accessing globally declared collection in multiple threads and modifying collection instance then exception will occur if collection is not thread safe.

The following sample uses threads and lock. As long as the lock statement is present, the statement block is a critical section and balance will never become a negative number.

  class Account
    {
        private Object thisLock = new Object();
        int balance;

        Random r = new Random();

        public Account(int initial)
        {
            balance = initial;
        }

        int Withdraw(int amount)
        {

            // This condition never is true unless the lock statement
            // is commented out.
            if (balance < 0) { throw new Exception("Negative Balance"); } // Comment out the next line to see the effect of leaving out // the lock keyword. lock (thisLock) { if (balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }

        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }

    class Test
    {
        static void Main()
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
        }
    }

Below download provide extended classes of ArrayList and Queue with wrapper around it to make it thread safe.
The wrapper implements the most common functions of these collection elements. You can add it in your class library and use it for threads.

Download:- SyncCollections.zip

3,447 total views, 1 views today

Thread safe collection in C# .Net
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *