On Mar 28, 11:48 pm, "Christof Nordiek" <c...@nospam.de wrote:
Hi Mark,
would it be a problem, if between the reads and the writes of one request
there are writes of other request?
If so, you should not lock on the Hashtable, while processing the data, but
only the writes and the reads.
Otherwise, you should try to limit the data locked, f.e. only lock the key
while processing. Not easy to do, if the key is of a value type. So, an
alternative would be, to use a class as data and lock on that instance.
OK... that beats my idea hands down.
Christof is right: you have two locking scenarios here:
1. Adding a new key to the hash table: need to lock the whole table.
2. Manipulating the data structure that is under one key: make it a
class and lock the instance in the hash table.
The very fact that you want to manipulate the data that's already in
the hash table, rather than just writing it once and possibly deleting
it later, says that you want these to be classes, not structs. Plus,
by making them classes, you get the added benefit that you can lock on
them.
So now you can have one thread updating one instance and another
thread updating another instance and they won't collide.
The only time you need to lock the whole thing is when you add a new
key and when you're fetching instances to update. If even this
contention is too much for you, then you can move to the solution I
proposed: roll your own hash table structure, and allow for locking on
individual hash buckets. If you do this, then the pseudo-code would
be: calculate hash value for GUID, calculate bucket index from hash
value, lock bucket, fetch data instance, lock data instance, unlock
bucket, update data instance, unlock data instance. This improves
concurrency because a thread that is manipulating / searching the hash
chain at bucket #15 isn't in contention for a lock with another thread
that is manipulating / searching the hash chain at bucket #3, and even
if threads are updating class instances in the same chain, they need
to lock the bucket only long enough to find the item they want to
update.
If you allow for deletions from the hash table, then the thread doing
the deletion has to lock both the table (or the bucket) _and_ the item
to be deleted, to ensure that nobody else is updating the item while
it's being deleted.