Top of the morning to you all!
I am just having a little trouble understanding thread synchronization. Allow me to demonstrate.
I have a class that exposes 3 methods like so:
Now I have declared an instance of 'class a' and multiple threads are able to perform actions upon it.Code:Class a Private x As Collection Public Sub Add() End Sub Public Sub Remove() End Sub Public Sub Print() For counter As Integer = 0 To x.Count-1 Step 1 Next counter End Sub End Class
My problem comes when one thread is running a print operation and another may be removing an item from the collection. The print operation is printing the data in a loop, when the loop began 'counter' was set to the count of the collection. The collection's size has since changed and we are headed for an "index out of bounds" error.
I need to lock the instance of the class as a whole so that only one thread can perform operations on the instance at any one time.
I know about the 'SyncLock' feature but am unsure if this is sufficient. Is the answer just to synclock the calls to the class methods? E.G...
Any pointers or leads would be greatly appreciated,Code:Dim objSync as Object SyncLock objSync instance.Print() End SyncLock
Have a great morning!
Matt.




Reply With Quote