nitrkli
nitrkli

Reputation: 369

How to correctly access ArrayList from threadpool?

I am using ThreadPool on my c# application and I need to add and remove items from an "global" ArrayList. The threads will be accessing the same ArrayList at any time. How should I do this in a safe way? So no threads will try to access the ArrayList at the same time.

I am starting the threads with this:

my_args args = new my_args(input, id, this);
ThreadPool.QueueUserWorkItem(new WaitCallback(generateKeywords), args);

Upvotes: 0

Views: 1727

Answers (4)

Elian Ebbing
Elian Ebbing

Reputation: 19027

You can create a thread safe wrapper around the ArrayList:

ArrayList list = new ArrayList();
ArrayList threadSafeList = ArrayList.Synchronized(list);

Note however that even with a synchronized ArrayList it is still not safe to enumerate through the list. See this msdn page for more information.

Can I ask why you use an ArrayList instead of a generic collection? If you use the list as a queue to feed a couple of worker processes, and you are using .net 4.0, then you can use a BlockingCollection<T> object. See this msdn page for more information.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564413

A better option, if you have .NET 4 available, would be to use one of the collections in System.Collections.Concurrent. These all provide thread safe reading and writing without explicitly locking.

(Some of these collections are lock free, some use fine grained locking, but they are all thread safe, without you having to worry about it.)

Upvotes: 0

Will
Will

Reputation: 928

I would use SyncRoot to lock the array.

lock(((ICollection)myArray).SyncRoot)
{

}

Upvotes: 1

Adi
Adi

Reputation: 5223

You may try to use lock statement with your array as argument:

lock(myArray){
//do what you want, your array will be protected in this block of code
}

Upvotes: 0

Related Questions