Threadsafe and generic arraylist?

心已入冬 提交于 2019-12-24 15:26:06

问题


I want to have a generic thread safe collection and I saw that the Arraylist can easily be used thread safe by its static Synchronized method but what bugs me is that this ArrayList is not generic so when I want to use my objects I always have to cast them. Is there an easier way to do this? Also other list types would be possible.


回答1:


A little knowledge is a dangerous thing ;-) Yes, you could use Meta-Knight's suggestion and use SyncRoot, but you need to be careful - it's not a panacea. See this post from the BCL Team Blog from Microsoft to see why it's not as simple as SyncRoot. Quotes from that post:

A few astute users of our generic collections observed that we no longer provide a public SyncRoot property on ICollection<T>

and

I think we're better off forcing people to think more heavily about synchronization, and frankly a SyncRoot property on our generic collections doesn't provide any value.

Of course, that's not to say it can't be used under any circumstances - you just have to think the use cases through carefully and not be on auto-pilot.




回答2:


If you read on MSDN regarding the synchronized method is still says this:

"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."




回答3:


You could create a List(T) wrapper and synchronize access with the SyncRoot property.

MSDN example:

ICollection ic = ...;
lock (ic.SyncRoot) 
{
    // Access the collection.
}


来源:https://stackoverflow.com/questions/1278010/threadsafe-and-generic-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!