• 0

[C#] Thread Safe Dictionary .NET 2.0


Question

Will this code make the dictionary thread-safe?

Each function hangs until the locked boolean clears (a write operation finishes).

Will it work? Thanks.

 public class SafeDictionary<TKey, TValue>
	{
		private bool						_bLocked = false;
		private Dictionary<TKey, TValue>	_dDictionary;

		public SafeDictionary()
		{
			_dDictionary = new Dictionary<TKey, TValue>();
		}

		private void WaitForUnlock()
		{
			while (_bLocked);
		}

		private void WaitForUnlock(int timeout)
		{
			while (_bLocked)
				Thread.Sleep(timeout);
		}

		public void Lock()
		{
			_bLocked = true;
		}

		public void Unlock()
		{
			_bLocked = false;
		}

		public void Add(TKey key, TValue value)
		{
			WaitForUnlock();

			Lock();
			_dDictionary.Add(key, value);
			Unlock();
		}

		public virtual ICollection<TValue> Values
		{
			get
			{
				WaitForUnlock();

				return _dDictionary.Values;
			}
		}

		public virtual ICollection<TKey> Keys
		{
			get
			{
				WaitForUnlock();

				return _dDictionary.Keys;
			}
		}

		public int Count
		{
			get
			{
				WaitForUnlock();

				return _dDictionary.Count;
			}
		}

		public void Clear()
		{
			WaitForUnlock();

			Lock();
			_dDictionary.Clear();
			Unlock();
		}

		public void Remove(TKey key)
		{
			WaitForUnlock();

			Lock();
			_dDictionary.Remove(key);
			Unlock();
		}

		public virtual TValue this[TKey key]
		{
			get
			{
				WaitForUnlock();

				return _dDictionary[key];
			}
			set
			{
				WaitForUnlock();

				Lock();
				_dDictionary[key] = value;
				Unlock();
			}
		}

		public virtual bool ContainsKey(TKey key)
		{
			WaitForUnlock();

			return _dDictionary.ContainsKey(key);
		}


		public virtual bool TryGetValue(TKey key, out TValue value)
		{
			WaitForUnlock();

			return _dDictionary.TryGetValue(key, out value);
		}
	}

Link to comment
https://www.neowin.net/forum/topic/792198-c-thread-safe-dictionary-net-20/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

Why not use .NET's built-in lock mechanism? In C#, that is lock(object). Doing something like

while (locked);

keeps the CPU busy for nothing, while

lock(privateVariable)

achieves the same effect while not using any unnecessary CPU cycles.

See http://msdn.microsoft.com/en-us/library/ms173179.aspx if you don't know what I'm talking about.

  • 0
  Dr_Asik said:
Why not use .NET's built-in lock mechanism? In C#, that is lock(object). Doing something like

while (locked);

keeps the CPU busy for nothing, while

lock(privateVariable)

achieves the same effect while not using any unnecessary CPU cycles.

See http://msdn.microsoft.com/en-us/library/ms173179.aspx if you don't know what I'm talking about.

Thanks for the replies...i started implementing the lock already. Do you have to lock for both read and write access or just when modifying the collection?

Thanks again.

  • 0

Several threads can read at the same time, but only one can write. So you don't need to lock for read access.

Not sure what you mean by "implementing the lock"... it is a built-in function in C#. You just need to provide it with a private class member, typically just an object.

  • 0

Consider using a private Object instance to serve as your lock instead of SyncRoot. The problem with SyncRoot is that anybody else could be holding that lock in an irresponsible fashion.

More discussion is available at: http://blogs.msdn.com/brada/archive/2003/09/28/50391.aspx

  • 0
  antareus said:
Consider using a private Object instance to serve as your lock instead of SyncRoot. The problem with SyncRoot is that anybody else could be holding that lock in an irresponsible fashion.

More discussion is available at: http://blogs.msdn.com/brada/archive/2003/09/28/50391.aspx

That's from 2003. :) At the bottom it reads "Rest assured we will not make the same mistake as we build the generic versions of these collections."

  • 0
  GreyWolfSC said:
That's from 2003. :) At the bottom it reads "Rest assured we will not make the same mistake as we build the generic versions of these collections."

Well by the mistake he means that they will try to deprecate the SyncRoot propery, which is the case now. The ICollection<T> interface does not contain SynRoot property and "lock(dictionaryClass.SyncRoot)" will not compile. You can cast the dictionaryClass to ICollection and then get SynRoot since the old non-genric ICollection interface has SyncRoot property, but the Dictionary<TKey, TValue> class implements it explicitly.

So as antareus said, use a private readonly object for locking.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • GPT-5 upgrade sparks backlash from ChatGPT Plus users over new usage limits by Pradeep Viswanathan OpenAI yesterday unveiled its highly anticipated GPT-5 model, featuring major advancements in reasoning, coding, and tool-calling capabilities. In a departure from previous launches, the company announced that this cutting-edge model will be accessible to all ChatGPT users, including those on the free tier. Depending on the ChatGPT subscription tier, GPT-5’s intelligence and usage limits will vary. Free-tier users will receive a limited number of high-intelligence responses, while Pro-tier users will have unlimited access. Here are the exact GPT-5 usage limits on ChatGPT: ChatGPT Free tier accounts can send up to 10 messages every 5 hours. After reaching this limit, ChatGPT will automatically use the GPT-5 mini until the limit resets. Free tier users also have access to just one GPT-5 Thinking message per day. ChatGPT Plus plans can send up to 80 messages every 3 hours. After reaching this limit, ChatGPT will switch to GPT-5 mini until the limit resets. ChatGPT Plus or Team users can manually select the GPT-5-Thinking model from the model picker with a usage limit of up to 200 messages per week. ChatGPT Pro plan offers unlimited access to GPT-5 models. If ChatGPT automatically switches from GPT-5 to GPT-5-Thinking, it will not count toward the above limits. While this may sound good, ChatGPT Plus subscribers are unhappy with the change. Previously, they had unlimited access to OpenAI’s o3 and o4-mini Thinking models, but they are now limited to just 200 messages per week. The only workaround for ChatGPT Plus users, for now, is to explicitly instruct the model to think longer through their prompts. It’s unclear how OpenAI will respond to this feedback from its core subscribers. Any future changes to the usage limits for Plus users could play a key role in keeping subscribers satisfied while balancing global demand for the GPT-5 model. Image Credit: Depositphotos.com
    • Guess I'll be saving the APK for future use, screw that data-harvesting copilot crap...
    • Looks like it, I have them working after the update.
    • MEmu Android Emulator 9.2.6 (offline installer) by Razvan Serea MEmu is a FREE Android emulator that brings fun of the Android experience to Microsoft Windows devices. It runs on nearly all Windows devices (PC, notebook, 2-in-1 devices, tablets). Comparing to other Android emulators, MEmu provides the highest performance and greatest compatibility. The richest features: Full Android experience with an elegant desktop Flexible customization (CPU#, memory size, resolution, device model, nav bar location, root mode, etc.) Mapping the keyboard / joystick to screen touch for much better game experience Passing through sensor data (e.g. accelerometer) to Android, so you can play car-racing like games intuitively GPS location simulation File sharing between Windows and Android Fast APK installation by drag and drop One-click Android system creation / clone / deleting, and you can run multiple Android instances simultaneously Using MEmu, you can: Have fun playing Android games on PC Chat more conveniently by using keyboard in Whatsapp, Wechat, etc. Watch live show and TV channels Ten seconds to start Directly open several Android Emulator windows MEmu Android Emulator 9.2.6 changelog: Optimized the emulator GUI to support native Windows 11 style. Optimized APK export speed, automatically export to shared directory, and display export progress. Fixed an issue where APK export could occasionally result in incomplete files on Android 12 instance. Fixed graphical corruption issues in Project Net game. Download: MEmu 9.2.6 Offline Installer | 639.0 MB (Freeware) View: MEmu Home Page | MEmu Support Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Yawdee earned a badge
      Week One Done
    • Week One Done
      eugwalker earned a badge
      Week One Done
    • First Post
      Ben Gross earned a badge
      First Post
    • One Month Later
      chiptuning earned a badge
      One Month Later
    • Week One Done
      harveycoleman123 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      657
    2. 2
      +FloatingFatMan
      188
    3. 3
      ATLien_0
      146
    4. 4
      Xenon
      133
    5. 5
      wakjak
      107
  • Tell a friend

    Love Neowin? Tell a friend!