What is the best approach to thread-safe multiple parallel readers threads and occasional writer thread on an ArrayList object to a C# application?
Conside开发者_StackOverflow中文版r the scenario below:
- The application is multi-threaded and it has one static ArrayList used globally.
- The application has one thread that reconstruct the ArrayList entirely from data read from database from time to time.
- The application has N threads reading from this global ArrayList in parallel.
What is the best approach to thread-safe the multiple parallel reads and the occasional altering of the ArrayList object?
I would look at using ReaderWriterLockSlim for that: http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx
If it contains a cache of readonly data read from a database and is never modified, you probably don't need any synchronisation.
You do of course need to construct the list completely before setting the global reference, e.g.:
private static ArrayList myList;
...
myList = GetListFromDatabase();
In the event of a race condition when a writer thread replaces the list, another thread can get the "old" copy of the list, but if it's not being modified this old copy will still be consistent.
Could you not simply make the Arraylist a static property of a class? Then provide get; set; accessors which wrap "lock(object objMutex) {...}" around the Arraylist object? This would then ensure that there was only synchronous access to the object across all threads.
Also you can look to the System.Collections.Concurrent (if you use .NET 4.0) This collections is optimised for multithreading. Good article about this container is .NET 4.0 and System.Collections.Concurrent.ConcurrentBag
精彩评论