[dba-VB] Thread safe list

jwcolby jwcolby at colbyconsulting.com
Fri Dec 3 07:14:30 CST 2010


I am using two threads in a part of my application.  One places objects onto a list for processing. 
  Another gets pointers to objects on the list for processing, and later removes those objects from 
the list when processing is complete.

 From my reading, this has to be synchronized with locking of some sort since a simultaneous write 
by one thread while reading by the other will cause corruption of some sort.

I have found discussions about how it is necessary to do so but no clear example of two different 
methods actually locking / unlocking the collection object.

In my class I have a class global dictionary object.

I have one (public) method called from outside of the class to place an object onto the list.  I 
have another (private) method called by the class to get an object on the list and use it.

Can I simply wrap the actual object with a lock in each method?

(obviously psuedocode)

	Dictionary<> Dict;

public void AddObjToList(obj)
{
	lock(Dict)
	{
		Dict.Add();
	}
}
private GetObjFromList()
{
	lock(Dict)
	{
		Obj = Dict[0];
	}

	Continue processing Obj here...
}


Will something this simple actually work?  Can someone provide simple psuedocode that shows how to 
do this?


-- 
John W. Colby
www.ColbyConsulting.com



More information about the dba-VB mailing list