473,327 Members | 1,896 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Thread-safe Dictionary

I am porting some code to use generics. Currently, we have a
synchronized Hashtable called as follows:

private Hashtable table = Hashtable.Synchronized (new Hashtable ());

What I would like to do is to port this to a Dictionary so that it can
be type-safe:

private Dictionary<string,stringtable = new Dictionary<string,string>
();

But this loses our synchronization. I was suprised to find that there
is no built-in method for an automatically synchronized Dictionary. So
what should I do?

Some options:

* add 'volatile' keyword to declaration
* wrap all modifications of the table with lock(table) { ... }
* use some other locking mechanism
* stick to using Hashtable for now, threading hurts my my head and its
better to just leave it alone and not break the whole thing :-)

Thanks!
Tamara

Sep 12 '06 #1
2 26427
Tamara,

The first option, adding the volatile keyword to the declaration will do
nothing for actually making the operations on the dictionary thread-safe.
It will only affect accessing the reference.

Your best option is to not touch anything. The performance of the
hashtable compared to the Dictionary<string, stringisn't going to be that
far off (not counting synchronization), since you are using reference types
for the key and the value, there is no boxing, and less of a performance
hit.

If you insist on using a Dictionary<string, string>, then I would create
an implementation of IDictionary<TKey, TValuewhich synchronizes calls made
to it internally.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

<ta*************@gmail.comwrote in message
news:11**********************@e63g2000cwd.googlegr oups.com...
>I am porting some code to use generics. Currently, we have a
synchronized Hashtable called as follows:

private Hashtable table = Hashtable.Synchronized (new Hashtable ());

What I would like to do is to port this to a Dictionary so that it can
be type-safe:

private Dictionary<string,stringtable = new Dictionary<string,string>
();

But this loses our synchronization. I was suprised to find that there
is no built-in method for an automatically synchronized Dictionary. So
what should I do?

Some options:

* add 'volatile' keyword to declaration
* wrap all modifications of the table with lock(table) { ... }
* use some other locking mechanism
* stick to using Hashtable for now, threading hurts my my head and its
better to just leave it alone and not break the whole thing :-)

Thanks!
Tamara

Sep 12 '06 #2
Here is a synced version below. I have to admit I did not test this fully.
Nor am I totally convinced that some of these methods really don't need a
lock (i.e. ContainsKey, Count, etc) - but I used SyncHashTable as a guide
there. To be totally sure, you could add the lock.

public class SafeDictionary<TKey, TValue: IDictionary<TKey, TValue>
{
private readonly object syncRoot = new object();
private Dictionary<TKey, TValued = new Dictionary<TKey, TValue>();

#region IDictionary<TKey,TValueMembers

public void Add(TKey key, TValue value)
{
lock (syncRoot)
{
d.Add(key, value);
}
}

public bool ContainsKey(TKey key)
{
return d.ContainsKey(key);
}

public ICollection<TKeyKeys
{
get
{
lock (syncRoot)
{
return d.Keys;
}
}
}

public bool Remove(TKey key)
{
lock (syncRoot)
{
return d.Remove(key);
}
}

public bool TryGetValue(TKey key, out TValue value)
{
lock (syncRoot)
{
return d.TryGetValue(key, out value);
}
}

public ICollection<TValueValues
{
get
{
lock (syncRoot)
{
return d.Values;
}
}
}

public TValue this[TKey key]
{
get
{
return d[key];
}
set
{
lock (syncRoot)
{
d[key] = value;
}
}
}

#endregion

#region ICollection<KeyValuePair<TKey,TValue>Members

public void Add(KeyValuePair<TKey, TValueitem)
{
lock (syncRoot)
{
((ICollection<KeyValuePair<TKey, TValue>>)d).Add(item);
}
}

public void Clear()
{
lock (syncRoot)
{
d.Clear();
}
}

public bool Contains(KeyValuePair<TKey, TValueitem)
{
return ((ICollection<KeyValuePair<TKey,
TValue>>)d).Contains(item);
}

public void CopyTo(KeyValuePair<TKey, TValue>[] array, int
arrayIndex)
{
lock (syncRoot)
{
((ICollection<KeyValuePair<TKey, TValue>>)d).CopyTo(array,
arrayIndex);
}
}

public int Count
{
get
{
return d.Count;
}
}

public bool IsReadOnly
{
get { return false; }
}

public bool Remove(KeyValuePair<TKey, TValueitem)
{
lock (syncRoot)
{
return ((ICollection<KeyValuePair<TKey,
TValue>>)d).Remove(item);
}
}

#endregion

#region IEnumerable<KeyValuePair<TKey,TValue>Members

public IEnumerator<KeyValuePair<TKey, TValue>GetEnumerator()
{
return ((ICollection<KeyValuePair<TKey,
TValue>>)d).GetEnumerator();
}

#endregion

#region IEnumerable Members

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)d).GetEnumerator( );
}

#endregion
}

--
William Stacey [MVP]

<ta*************@gmail.comwrote in message
news:11**********************@e63g2000cwd.googlegr oups.com...
|I am porting some code to use generics. Currently, we have a
| synchronized Hashtable called as follows:
|
| private Hashtable table = Hashtable.Synchronized (new Hashtable ());
|
| What I would like to do is to port this to a Dictionary so that it can
| be type-safe:
|
| private Dictionary<string,stringtable = new Dictionary<string,string>
| ();
|
| But this loses our synchronization. I was suprised to find that there
| is no built-in method for an automatically synchronized Dictionary. So
| what should I do?
|
| Some options:
|
| * add 'volatile' keyword to declaration
| * wrap all modifications of the table with lock(table) { ... }
| * use some other locking mechanism
| * stick to using Hashtable for now, threading hurts my my head and its
| better to just leave it alone and not break the whole thing :-)
|
| Thanks!
| Tamara
|
Sep 12 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: adeger | last post by:
Having trouble with my first forays into threads. Basically, the threads don't seem to be working in parallel (or you might say are blocking). I've boiled my problems to the following short code...
4
by: Gilles Leblanc | last post by:
Hi I have started a small project with PyOpenGL. I am wondering what are the options for a GUI. So far I checked PyUI but it has some problems with 3d rendering outside the Windows platform. I...
7
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates...
4
by: Matthew Groch | last post by:
Hi all, I've got a server that handles a relatively high number of concurrent transactions (on the magnitude of 1000's per second). Client applications establish socket connections with the...
5
by: Razzie | last post by:
Hi all, A question from someone on a website got me thinking about this, and I wondered if anyone could explain this. A System.Threading.Timer object is garbage collected if it has no...
16
by: droopytoon | last post by:
Hi, I start a new thread (previous one was "thread timing") because I have isolated my problem. It has nothing to do with calling unmanaged C++ code (I removed it in a test application). I...
9
by: mareal | last post by:
I have noticed how the thread I created just stops running. I have added several exceptions to the thread System.Threading.SynchronizationLockException System.Threading.ThreadAbortException...
13
by: Bob Day | last post by:
Using vs2003, vb.net I start a thread, giving it a name before start. Code snippet: 'give each thread a unique name (for later identification) Trunk_Thread.Name = "Trunk_0_Thread" ' allow...
7
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have...
3
by: John Nagle | last post by:
There's no way to set thread priorities within Python, is there? We have some threads that go compute-bound, and would like to reduce their priority slightly so the other operations, like...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.