开发者

List<T> multiple writer thread safety

If I have multiple threads calling the Add method of a List object, and no readers, do I only need to lock on the List object b开发者_JAVA技巧efore calling Add to be thread safe?


Usually it's best to lock on a separate (immutable) object... locking on the same object you're modifying is bad practice should be done with caution.

private readonly object sync = new object();
private List<object> list = new List<object>();

void MultiThreadedMethod(object val)
{
    lock(sync)
    {
        list.Add(val);
    }
}

In a basic case like this you will not have a problem, but if there is a possibility that your list can be changed (not the contents of the list, but the list itself), then you might have a situation where you lock on two objects when you only intend to lock on one.


Yes. But you might also consider subclassing the List and "new" over the Add method. That will allow you to encapsulate the lock. It will work great as long as nothing accesses the base List. This technique is used for simple tree structures in XNA video games.


Yes, you need to lock. Instance methods are not guaranteed to be thread safe on List<T>.


I think these have been linked before on here, but I found them to be very useful and interesting:

Thread safe collections are hard

Thread safe collection

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜