清除列表的问题< T> [英] Problem with clearing a List<T>

查看:96
本文介绍了清除列表的问题< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么当我清除一个 System.Collections.Generic.List< T> IndexOutOfRangeException c $ c>。这是否有意义?

I don't know why I have an IndexOutOfRangeException when I am clearing a System.Collections.Generic.List<T>. Does this make sense?

List<MyObject> listOfMyObject = new List<MyObject>();
listOfMyObject.Clear(); 


推荐答案

如果多个线程同时访问列表,通常会发生。如果一个线程删除一个元素,而另一个调用Clear(),则可能会发生此异常。

This typically happens if multiple threads are accessing the list simultaneously. If one thread deletes an element while another calls Clear(), this exception can occur.

在这种情况下,答案是正确同步,您的列表访问。

The "answer" in this case is to synchronize this appropriately, locking around all of your List access.

编辑:

为了处理这个,最简单的方法是将您的列表封装在自定义类中,并公开所需的方法,但需要锁定。您需要为更改收藏的任何内容添加锁定。

In order to handle this, the simplest method is to encapsulate your list within a custom class, and expose the methods you need, but lock as needed. You'll need to add locking to anything that alters the collection.

这将是一个简单的选项:

This would be a simple option:

public class MyClassCollection
{
    // Private object for locking
    private readonly object syncObject = new object(); 

    private readonly List<MyObject> list = new List<MyObject>();
    public this[int index]
    {
        get { return list[index]; }
        set
        {
             lock(syncObject) { 
                 list[index] = value; 
             }
        }
    }

    public void Add(MyObject value)
    {
         lock(syncObject) {
             list.Add(value);
         }
    }

    public void Clear()
    {
         lock(syncObject) {
             list.Clear();
         }
    }
    // Do any other methods you need, such as remove, etc.
    // Also, you can make this class implement IList<MyObject> 
    // or IEnumerable<MyObject>, but make sure to lock each 
    // of the methods appropriately, in particular, any method
    // that can change the collection needs locking
}

这篇关于清除列表的问题&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆