You are here

Dictionary and Thread safety in C#

Dictionary is not thread safe. Must be locked when manipulating dictionary. Remove the lock statement in the following example and try.


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

namespace DictionaryExample
{
    public class DictionaryItem
    {
        private string name;
        private int counter;

        public DictionaryItem(string s, int c)
        {
            name = s;
            counter = c;
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public int Counter
        {
            get
            {
                return counter;
            }
            set
            {
                counter = value;
            }
        }
    }
    class Program
    {
        static Dictionary dictionary = new Dictionary();
        static object threadLock = new object();
        static void Main(string[] args)
        {
            for (int i = 0; i  Thread3(dictionary));
            t.Start();

            Thread t2 = new Thread(() => Thread4(dictionary));
            t2.Start();

            Thread t11 = new Thread(() => Thread3(dictionary));
            t11.Start();

            Thread t22 = new Thread(() => Thread4(dictionary));
            t22.Start();

            Timer tmr1 = new Timer(TimerThread1, "timer 1...", 1, 10);
            //tmr1.Dispose();

            Timer tmr2 = new Timer(TimerThread2, "timer 2...", 5, 50);
            //tmr2.Dispose();

            for (int i = 0; i  Thread3(dictionary)).Start();
            }

            Console.WriteLine("Main Done, reading back 10 items");
            for (int i = 0; i 

This example shows usages of lock for manipulating dictionary data type.