summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/SynchronizedList.cs
blob: ad98f198a7e5c799ae0abe6478af26fa7bd2a499 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Xamarin.Forms
{
	internal class SynchronizedList<T> : IList<T>, IReadOnlyList<T>
	{
		readonly List<T> _list = new List<T>();
		ReadOnlyCollection<T> _snapshot;

		public void Add(T item)
		{
			lock (_list)
			{
				_list.Add(item);
				_snapshot = null;
			}
		}

		public void Clear()
		{
			lock (_list)
			{
				_list.Clear();
				_snapshot = null;
			}
		}

		public bool Contains(T item)
		{
			lock (_list)
				return _list.Contains(item);
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			lock (_list)
				_list.CopyTo(array, arrayIndex);
		}

		public int Count
		{
			get { return _list.Count; }
		}

		bool ICollection<T>.IsReadOnly
		{
			get { return false; }
		}

		public bool Remove(T item)
		{
			lock (_list)
			{
				if (_list.Remove(item))
				{
					_snapshot = null;
					return true;
				}

				return false;
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public IEnumerator<T> GetEnumerator()
		{
			ReadOnlyCollection<T> snap = _snapshot;
			if (snap == null)
			{
				lock (_list)
					_snapshot = snap = new ReadOnlyCollection<T>(_list.ToList());
			}

			return snap.GetEnumerator();
		}

		public int IndexOf(T item)
		{
			lock (_list)
				return _list.IndexOf(item);
		}

		public void Insert(int index, T item)
		{
			lock (_list)
			{
				_list.Insert(index, item);
				_snapshot = null;
			}
		}

		public T this[int index]
		{
			get
			{
				ReadOnlyCollection<T> snap = _snapshot;
				if (snap != null)
					return snap[index];

				lock (_list)
					return _list[index];
			}

			set
			{
				lock (_list)
				{
					_list[index] = value;
					_snapshot = null;
				}
			}
		}

		public void RemoveAt(int index)
		{
			lock (_list)
			{
				_list.RemoveAt(index);
				_snapshot = null;
			}
		}
	}
}