|
-
Aug 23rd, 2003, 05:58 PM
#1
Thread Starter
Hyperactive Member
Need the Threading Gurus Please!!
Might anyone out here help me by answering a few threading questions that I can't seem to find anywhere. My question deals with Dictionary Objects (Array List, HashTable, Collections) and reading, writing, and iterating through them safely in different threads. Ok here is what the documentation says about Hashtables and threading...
To support one or more writers, all operations on the Hashtable must be done through the wrapper returned by the Synchronized method.
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
So the first part of my question is.. Is this a safe way to declare a syncronized wrapped hashtable?
VB Code:
'This is declared in the scope of a Class
Private Accounts As Hashtable = Hashtable.Synchronized(New Hashtable)
Or do I need to create a normal Hashtable in the Class's Global scope then declare a new sycnronized wrapper in each method I call that works with the data in the hashtable?
Next Question...
The docs clearly state that you shouldn't enumerate through a hashtable even if its wrapped in a syncronized wrapper without specifically Locking the iteration first.. So My question is..
If I'm locking the Hash Table during Iteration like so in one thread:
VB Code:
SyncLock Accounts.SyncRoot
For Each a As Account In Accounts
...Code Here...
Next
End SyncLock
But a method in another thread is adding a object at the same time like so:
VB Code:
Accounts.Add(AcctID, Acct)
Wouldn't I need BOTH methods to have the hashtable SyncLocked to be thread safe? Or will that work with JUST locking during enumerating and letting the syncronized wrapper handle syncronizing during adds and removes?
It just seems to me that SyncLocks work in conjunction with one another. So if I have the hashtable locked during Enumeration in one method, I can still access it, read from it, write to it, and remove from it on another method so long as I don't lock it in the second method. This will cause the first one to error out even though it's wrapped and locked...
So what's the point of even wrapping the hashtable in a syncronized wrapper if I'm going to have to end up SyncLocking every line of code that manipulates the data in the hashtable??
I know that this probably doesn't make a whole bunch of sense if you aren't famailiar with it but any help would be appretiated
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|