Is LinkedList Implementation of .Net threadsafe?
Actually I am working on an application which uses multiple threads to work on number of tasks and the parent application receives the output of the task, later to be written to files, currently I am using arraylist to append output to, but that happens to be slow when removing items from queue. I was thinking to convert arraylist part to linkedlist for optimized reads and clears, can 开发者_StackOverflow中文版anyone confirm we me if linkedList Implementation of .Net is threadsafe or even using arraylist was threadsafe?
The reference states that:
This type is not thread safe. If the LinkedList(Of T) needs to be accessed by multiple threads, you will need to implement their own synchronization mechanism.
A LinkedList(Of T) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
EDIT:
As for ArrayList, the reference states:
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
An ArrayList can support multiple readers concurrently, as long as the collection is not modified. To guarantee the thread safety of the ArrayList, all operations must be done through the wrapper returned by the Synchronized method.
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
Since you tagged it C#4, use the BlockingCollection<T>
.
It is Thread-safe and will allow you to throttle traffic when needed.
This collection class was designed for the task. But Performance of the collection should not really matter when you eventually write to File .
Any thread safe collection under namespace System.Collections.Concurrent should do the job for you. However, from a perf point of view, I do not think these will perform better than Array considering that there will be some syncroniazation overhead. Your two request thread-safetiness and performance might not be achieveable at the same time, you might need to come to some trade-off point
For more, see http://msdn.microsoft.com/en-us/library/dd267265.aspx
精彩评论