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(generat开发者_JAVA技巧eKeywords), args);
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.
I would use SyncRoot to lock the array.
lock(((ICollection)myArray).SyncRoot)
{
}
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
}
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.)
精彩评论