Re: Thread safety help on Hashtable
- From: Pavel Minaev <int19h@xxxxxxxxx>
- Date: Tue, 3 Mar 2009 17:46:17 -0800 (PST)
On Mar 3, 5:36 pm, mattd0878-use...@xxxxxxxxx wrote:
I'm sort of unclear on what is thread safe and what isn't when using
Hashtable. The way I understand the documentation is that multiple
threads can simultaneously be reading an instance of Hashtable while
at the same time a single thread is writing to it. Is this correct?
Yes.
The second part of my question is what exactly is considered a "write"
if I've added a reference object as the value? Is it just calls to
Hashtable methods like .Add and .Remove as well as setting the key to
a new value? Can I safely modify or reassign the reference object in
the Hashtable value? So for instance is this code thread safe?
What's not fine is anything that modifies the hashtable itself. Note
that the hashtable contains references to objects, not objects
themselves - so modifying fields of those objects does not modify the
hashtable (though it does mess things up if the modified fields are
used in GetHashCode() for the object - but this is separate, and
regardless of any threading issues).
class Server
{
public IPEndPoint serverEndPoint;
}
Hashtable ht = new Hashtable();
Server server = new Server();
server.serverEndPoint = new IPEndPoint(123456, 8000);
ht.Add(1, server);
server.serverEndPoint.Port = 8001;
Maybe ok, maybe not - depends on the implementation of
IPEndPoint.GetHashCode(). Regardless, no threading issues here.
What about?
class Server
{
public IPEndPoint serverEndPoint;
}
Hashtable ht = new Hashtable();
Server server = new Server();
server.serverEndPoint = new IPEndPoint(123456, 8000);
ht.Add(1, server);
server = new Server();
server.serverEndPoint = new IPEndPoint(123456, 8001);
This is definitely fine. You add the value of variable "server" -
which was a reference to some object - to the hashtable. The variable
itself is not linked to hashtable in any way, so when you later change
it (to reference a new object), this has no effect on the hashtable.
By the way, are you only using Hashtable, and not
Dictionary<TKey,TValue>, because you want to get locking for free?
.
- Follow-Ups:
- Re: Thread safety help on Hashtable
- From: Peter Morris
- Re: Thread safety help on Hashtable
- From: MattD
- Re: Thread safety help on Hashtable
- References:
- Thread safety help on Hashtable
- From: mattd0878-usenet
- Thread safety help on Hashtable
- Prev by Date: Thread safety help on Hashtable
- Next by Date: InvokeMember memory leak .NET 2
- Previous by thread: Thread safety help on Hashtable
- Next by thread: Re: Thread safety help on Hashtable
- Index(es):
Relevant Pages
|