简体   繁体   中英

Enumerating Observable Collection from another thread while being updated c#

我有一个类型为Observable collection的Property,它返回另一个属性collection。当我通过访问它从另一个类枚举该属性时,我得到了collection被修改的异常。我试图锁定该属性,但它似乎不起作用。帮助赞赏

You should ensure the ObservableCollection is enumerated end edited from the UI Thread. In order to do so use it like this:

Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
    MyCollection.Add(new Item());
}

Taking a lock on an object won't do anything unless someone else also takes a lock on the same object. If you absolutely must access this collection from a background thread then you should make sure that both the thread enumerating the collection and the thread modifying the collection have locks on the same objecs.

Its also considered good practice to lock on dedicated locking objects rather than on publicly accessible objects, eg

public class MyClass
{
    private object _mylock = new object();
    private ObservableCollection<string> _myCollection = new ObservableCollection<string>();

    public void DoEnumerate()
    {
        lock (_mylock)
        {
            foreach (var item in _myCollection)
            {
                // Do something
            }
        }
    }

    public void Modify()
    {
        lock (_mylock)
        {
            // Modify the collection here
        }
    }
}

If you are writing a GUI application then generally it is better to only modify the collection on the UI thread - if you need to do some background processing on the collection then consider taking a copy of the collection (eg an array) on the UI thread which the background thread then does its processing with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM