[dba-VB] Thread safe list

jwcolby jwcolby at colbyconsulting.com
Fri Dec 3 07:57:06 CST 2010


OK, two questions:

1) Does it have to be static?
2) My "GetObjFromList" actually uses a foreach().  It seems that is not going to work so well... 
Basically all of the work is done inside of that ForEach which would block the thread placing 
objects onto the list for long periods.

Is it possible to somehow use ForEach and lock of the object being iterated or am I going to have to 
move to a do loop construct where I lock / grab an object / process?

John W. Colby
www.ColbyConsulting.com

On 12/3/2010 8:40 AM, Shamil Salakhetdinov wrote:
> Hi John --
>
> I do use a dedicated static object instance to lock shared lists,
> dictionaries, ...
>
> (obviously psuedocode)
>
> 	Dictionary<>  Dict;
> private static object _dictLocker = new object();
>
> public void AddObjToList(obj)
> {
> 	lock(_dictLocker)
> 	{
> 		Dict.Add();
> 	}
> }
> private GetObjFromList()
> {
> 	lock(_dictLocker)
> 	{
> 		Obj = Dict[0];
> 	}
>
> 	Continue processing Obj here...
> }
>
>
> Thank you.
>
> --
> Shamil
>
> -----Original Message-----
> From: dba-vb-bounces at databaseadvisors.com
> [mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of jwcolby
> Sent: 3 ??????? 2010 ?. 16:15
> To: VBA
> Subject: [dba-VB] Thread safe list
>
> 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?
>
>



More information about the dba-VB mailing list