.NET Synchronised Dictionary(dotnet.dzone.com)

submitted by volume4volume4(910) 3 years, 11 months ago

In .NET 2.0 and above the SyncRoot was removed from the Dictionary and Hastable classes which meant you can't create thread-safe versions of these anymore. So here I provide a simple implementation of a generic synchronised dictionary class that is thread-safe, this was developed in .NET 3.5 using the new Threading.ReaderWriterLockSlim class.

1 comment |category: |Views: 10

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by gregbeechgregbeech(76) 3 years, 11 months ago 0

It's not actually thread-safe though:

if (dictionary.ContainsKey(someKey))
{
var value = dictionary[someKey]; // could throw as the key has been removed by another thread after the check
}

This is why the SyncRoot property was removed from the collections in the first place, because it was synchronising at too low a level. A thread-safe version would not have either of those APIs, and would instead implement something like

bool dictionary.TryGetValue(out TValue value);

Reply

information Login or create an account to comment on this story