newbie: thread safety of arraylist

J

Jeff

IDE: vs.net 2003
OS: XP pro sp2

I've got a class which contains an ArrayList object... This class will add
items to this ArrayList..... Once every minute another thread will start
and remove (based on some criteria) some items from the array... So
simultaneously as a method in one thread adds an item to the ArrayList
another thread wants to remove an item....

How should I program this?... Below is a simplified version of my code, I'm
not sure if this is the correct way of doing it...

public class Test : object
{
private ArrayList testArray;
public Test()
{
testArray = new ArrayList;

///Here I create another ArrayList:
ArrayList mySyncdAL = ArrayList.Synchronized( testArray );
...
...
}

Based on the constructor above, do you think the example below works:????

Thread A:
testArray.Add(value); //value here is just representing a
parameter, the code is simplefied

Thread B:
mySyncdAL.RemoveAt(pos)

Comments please?

Jeff
 
M

Maqsood Ahmed

Hello,
after synchronizing the list you should lock arraylist object's
SyncRoot while adding and removing items from it.

lock(al.SyncRoot)
{
//add or remove.
}

HTH. Cheers.
Maqsood Ahmed [MCP,C#]
Kolachi Advanced Technologies
http://www.kolachi.net
 
E

esafran

Yup, Thats exactly the way to do it...
You don't need to explicitly inherit from object, it does that by
default.

shorter version of the code:

public class Test
{
private ArrayList m_Array = ArrayLisy.Synchronized(new
ArrayList());
public Test()
{
}
}

The static method Synchronized "Returns a list wrapper that is
synchronized (thread-safe)." (taken from MSDN)

Cheers.
 
E

esafran

Hi,

You are not quite right.
After you have Syncronized the ArrayList, you don't need to lock the
SyncRoot object for single operations.

however, if you intend to enumerate your collection or perform multiple
operations which must be sequential, you must lock it.

public class Test
{
private ArrayList m_Array = ArrayLisy.Synchronized(new
ArrayList());
public Test()
{
}

public void Print()
{
lock (m_Array.SyncRoot)
{
IEnumerator enumerator = m_Array.GetEnumerator();
while(enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current.ToString());
}
}
}
}

Eyal.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top