aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/SynchronizedObservableCollection.cs
blob: b12c48ded7b4b05d601529b28b5885dd13d90dbe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Threading;

namespace Tango.Core
{
    public class SynchronizedObservableCollection<T> : ObservableCollection<T>
    {
        private static object _sync_lock = new object();
        private static object _modify_lock = new object();

        public SynchronizedObservableCollection() : base()
        {
            BindingOperations.EnableCollectionSynchronization(this, _sync_lock);
        }

        public SynchronizedObservableCollection(IEnumerable<T> collection) : base(collection)
        {
            BindingOperations.EnableCollectionSynchronization(this, _sync_lock);
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            SynchronizedObservableCollectionDispatcher.Invoke(() =>
            {
                lock (_modify_lock)
                {
                    base.OnCollectionChanged(e);
                }
            });
        }

        protected override void InsertItem(int index, T item)
        {
            lock (_modify_lock)
            {
                base.InsertItem(index, item);
            }
        }

        protected override void RemoveItem(int index)
        {
            lock (_modify_lock)
            {
                base.RemoveItem(index);
            }
        }

        protected override void ClearItems()
        {
            lock (_modify_lock)
            {
                base.ClearItems();
            }
        }
    }

    internal static class SynchronizedObservableCollectionDispatcher
    {
        internal static Dispatcher Dispatcher { get; set; }

        static SynchronizedObservableCollectionDispatcher()
        {
            if (Application.Current != null)
            {
                Dispatcher = Application.Current.Dispatcher;
            }
        }

        internal static void Invoke(Action action)
        {
            if (Dispatcher != null)
            {
                Dispatcher.BeginInvoke(action);
            }
            else
            {
                action();
            }
        }
    }
}