C# 重写 ObservableCollection 改成线程安全。 提供所有方法, 外面写好的业务不需要改变
Jump to turn (6)
- User
C# 重写 ObservableCollection 改成线程安全。 提供所有方法, 外面写好的业务不需要改变
- Assistant
C# 重写 ObservableCollection 改成线程安全。 提供所有方法, 外面写好的业务不需要改变
要使 ObservableCollection<T> 线程安全,你可以通过创建自己的线程安全版本来覆盖其基本功能。这可以通过使用锁来确保对集合的操作是线程安全的。以下是一个简单的示例,展示了如何创建一个自定义的线程安全的 ObservableCollection<T>:
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections;
using System.Threading;
public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
protected override void ClearItems()
{
_lock.EnterWriteLock();
try
{
base.ClearItems();
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void InsertItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
base.InsertItem(index, item);
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void RemoveItem(int index)
{
_lock.EnterWriteLock();
try
{
base.RemoveItem(index);
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void SetItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
base.SetItem(index, item);
}
finally
{
_lock.ExitWriteLock();
}
}
public new T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
return base[index];
}
finally
{
_lock.ExitReadLock();
}
}
set
{
_lock.EnterWriteLock();
try
{
base[index] = value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void MoveItem(int oldIndex, int newIndex)
{
_lock.EnterWriteLock();
try
{
base.MoveItem(oldIndex, newIndex);
}
finally
{
_lock.ExitWriteLock();
}
}
public new bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return base.Contains(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return base.IndexOf(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
base.CopyTo(array, arrayIndex);
}
finally
{
_lock.ExitReadLock();
}
}
public new int Count
{
get
{
_lock.EnterReadLock();
try
{
return base.Count;
}
finally
{
_lock.ExitReadLock();
}
}
}
protected override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged += value;
}
finally
{
_lock.ExitWriteLock();
}
}
remove
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged -= value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (var scope = _lock.ReadLock())
{
base.OnCollectionChanged(e);
}
}
}
public static class ReaderWriterLockSlimExtensions
{
public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
return new ActionOnDispose(rwLock.ExitReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterWriteLock();
return new ActionOnDispose(rwLock.ExitWriteLock);
}
private class ActionOnDispose : IDisposable
{
private readonly Action _action;
public ActionOnDispose(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
在这个实现中,我们使用 ReaderWriterLockSlim 来确保线程安全。所有对集合的更改操作,比如插入、移除和设置项,都被放置在写锁期间。读取操作,例如访问计数和检查是否包含某个项,则使用读锁来进行保护。这样,在不改变已有的业务逻辑的前提下,确保了线程安全。
添加 insert delete where 等等常用的方法呢
在 ObservableCollection<T> 中,已经定义了一些基本操作方法,比如 Add、Remove 等。如果需要添加类似的功能(如 Insert、Delete、Where 等),你可以通过扩展的方法或自定义方法实现。这是一个改进后的版本,其中包含了类似于 Where 和 Delete 等操作。
方法名需要保留原来一样的, 不需要修改外面已经实现的代码。 实现所有方法
为了使你的 ObservableCollection<T> 线程安全,并且保留原有的接口(方法名、参数等),我们可以覆盖 ObservableCollection<T> 的常用方法,并确保这些操作是线程安全的。下面的代码展示了一个可供参考的实现,同时尽量保留了 ObservableCollection<T> 的接口:
Tolist好像也需要
在多线程环境中,如果你想要线程安全地获取集合的快照(比如通过 ToList() 来实现),你需要确保在读取过程中集合没有被修改。为此,你可以在获取快照时使用读锁。
为 ThreadSafeObservableCollection<T> 添加一个 ToList 方法,如下所示:
where呢
对于 Where 方法,我们可以提供一个线程安全的实现,类似于 ToList(),通过使用读锁来保护集合读取过程。这样,我们可以确保条件筛选操作在数据不变的情况下进行。
下面是一个包含线程安全 Where 方法的完整示例:
public static class ReaderWriterLockSlimExtensions { public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock) { rwLock.EnterReadLock(); System.Threading.LockRecursionException:“如果写入锁定保持在此模式,可能无法获取读取锁定。” return new ActionOnDispose(rwLock.ExitReadLock); }
出现 LockRecursionException 可能是由于尝试在当前已经持有写锁的线程中获取读锁。ReaderWriterLockSlim 默认不允许锁的重入,也就是说,你不能在一个线程上同时持有读锁和写锁。
如果你希望在相同的线程中允许锁的重入,你可以在创建 ReaderWriterLockSlim 时启用锁的重入。例如:
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
这将允许一个线程进入锁的不同模式(读与写),尽管这通常不是推荐的做法,因为它可能导致死锁或逻辑错误。
设计考虑:首先考虑设计是否真的需要同一线程持有多个锁模式。如果可能,尽量简化锁的使用模式,避免在锁持有期间调用可能需要其他锁的操作。
日志和调试:添加日志和调试信息,帮助确认锁的状态和代码路径,以便更好地理解何时和如何获取锁。这可以在开发和调试阶段暴露潜在的竞争条件或死锁风险。
使用重入锁策略:如果发现的确有必要(例如,外部代码调用受保护的方法,且这些方法可能相互调用),则启用重入策略:
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
下面是修正后的代码:
Not yet included in a published release.
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
protected override void ClearItems()
{
_lock.EnterWriteLock();
try
{
base.ClearItems();
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void InsertItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index <= base.Count)
base.InsertItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void RemoveItem(int index)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.RemoveItem(index);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void SetItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.SetItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
public new T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= 0 && index < base.Count)
return base[index];
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitReadLock();
}
}
set
{
SetItem(index, value);
}
}
protected override void MoveItem(int oldIndex, int newIndex)
{
_lock.EnterWriteLock();
try
{
if (oldIndex >= 0 && newIndex >= 0 && oldIndex < base.Count && newIndex <= base.Count)
base.MoveItem(oldIndex, newIndex);
else
throw new ArgumentOutOfRangeException();
}
finally
{
_lock.ExitWriteLock();
}
}
public new bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return base.Contains(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return base.IndexOf(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
base.CopyTo(array, arrayIndex);
}
finally
{
_lock.ExitReadLock();
}
}
public new int Count
{
get
{
_lock.EnterReadLock();
try
{
return base.Count;
}
finally
{
_lock.ExitReadLock();
}
}
}
protected override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged += value;
}
finally
{
_lock.ExitWriteLock();
}
}
remove
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged -= value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (_lock.ReadLock())
{
base.OnCollectionChanged(e);
}
}
public IEnumerable<T> Where(Func<T, bool> predicate)
{
_lock.EnterReadLock();
try
{
return this.ToList().Where(predicate);
}
finally
{
_lock.ExitReadLock();
}
}
public void DeleteAll(Func<T, bool> predicate)
{
_lock.EnterWriteLock();
try
{
var itemsToRemove = this.Where(predicate).ToList();
foreach (var item in itemsToRemove)
{
base.Remove(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
public void AddRange(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items)
{
base.Add(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
}
public static class ReaderWriterLockSlimExtensions
{
public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
return new ActionOnDispose(rwLock.ExitReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterWriteLock();
return new ActionOnDispose(rwLock.ExitWriteLock);
}
private class ActionOnDispose : IDisposable
{
private readonly Action _action;
public ActionOnDispose(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
Where(Func<T, bool> predicate): 这个方法允许你在集合中筛选满足条件的元素。它是线程安全的,并返回一个满足条件的元素的集合。
DeleteAll(Func<T, bool> predicate): 这个方法删除集合中所有满足指定条件的元素,确保进行线程安全的写入操作。
AddRange(IEnumerable<T> items): 这个方法一次性添加多个元素,帮助减少多次调度锁定的开销。
这些方法使集合更强大,同时保持线程安全。这可以帮助减少多线程环境中常见的并发问题。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
protected override void ClearItems()
{
_lock.EnterWriteLock();
try
{
base.ClearItems();
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void InsertItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index <= base.Count)
base.InsertItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void RemoveItem(int index)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.RemoveItem(index);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void SetItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.SetItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
public new T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= 0 && index < base.Count)
return base[index];
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitReadLock();
}
}
set
{
SetItem(index, value);
}
}
protected override void MoveItem(int oldIndex, int newIndex)
{
_lock.EnterWriteLock();
try
{
if (oldIndex >= 0 && newIndex >= 0 && oldIndex < base.Count && newIndex <= base.Count)
base.MoveItem(oldIndex, newIndex);
else
throw new ArgumentOutOfRangeException();
}
finally
{
_lock.ExitWriteLock();
}
}
public new bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return base.Contains(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return base.IndexOf(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
base.CopyTo(array, arrayIndex);
}
finally
{
_lock.ExitReadLock();
}
}
public new int Count
{
get
{
_lock.EnterReadLock();
try
{
return base.Count;
}
finally
{
_lock.ExitReadLock();
}
}
}
protected override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged += value;
}
finally
{
_lock.ExitWriteLock();
}
}
remove
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged -= value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (_lock.ReadLock())
{
base.OnCollectionChanged(e);
}
}
public void AddRange(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items)
{
base.Add(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
public void Remove(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items.Where(i => base.Contains(i)))
{
base.Remove(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
private static class ReaderWriterLockSlimExtensions
{
public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
return new ActionOnDispose(rwLock.ExitReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterWriteLock();
return new ActionOnDispose(rwLock.ExitWriteLock);
}
private class ActionOnDispose : IDisposable
{
private readonly Action _action;
public ActionOnDispose(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
}
基本方法:确保 InsertItem, SetItem, RemoveItem, ClearItems 等操作是在写锁的保护之下进行,以确保线程安全。
辅助方法:
AddRange(IEnumerable<T> items): 用于添加多个项。Remove(IEnumerable<T> items): 用于移除集合中存在的多个项。线程安全锁定:通过 ReaderWriterLockSlim 和扩展方法 ReadLock 和 WriteLock 实现线程安全锁定。这些方法简化了锁的使用,确保锁定和解锁机制。
以上实现覆盖了原有的 ObservableCollection<T> 的基本方法,保持了原有方法名,使得现有的业务逻辑无需更改即可直接使用这个线程安全的版本。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
protected override void ClearItems()
{
_lock.EnterWriteLock();
try
{
base.ClearItems();
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void InsertItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index <= base.Count)
base.InsertItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void RemoveItem(int index)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.RemoveItem(index);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void SetItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.SetItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
public new T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= 0 && index < base.Count)
return base[index];
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitReadLock();
}
}
set
{
SetItem(index, value);
}
}
protected override void MoveItem(int oldIndex, int newIndex)
{
_lock.EnterWriteLock();
try
{
if (oldIndex >= 0 && newIndex >= 0 && oldIndex < base.Count && newIndex <= base.Count)
base.MoveItem(oldIndex, newIndex);
else
throw new ArgumentOutOfRangeException();
}
finally
{
_lock.ExitWriteLock();
}
}
public new bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return base.Contains(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return base.IndexOf(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
base.CopyTo(array, arrayIndex);
}
finally
{
_lock.ExitReadLock();
}
}
public new int Count
{
get
{
_lock.EnterReadLock();
try
{
return base.Count;
}
finally
{
_lock.ExitReadLock();
}
}
}
protected override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged += value;
}
finally
{
_lock.ExitWriteLock();
}
}
remove
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged -= value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (_lock.ReadLock())
{
base.OnCollectionChanged(e);
}
}
public List<T> ToList()
{
_lock.EnterReadLock();
try
{
return new List<T>(this);
}
finally
{
_lock.ExitReadLock();
}
}
public void AddRange(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items)
{
base.Add(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
public void Remove(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items.Where(i => base.Contains(i)))
{
base.Remove(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
private static class ReaderWriterLockSlimExtensions
{
public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
return new ActionOnDispose(rwLock.ExitReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterWriteLock();
return new ActionOnDispose(rwLock.ExitWriteLock);
}
private class ActionOnDispose : IDisposable
{
private readonly Action _action;
public ActionOnDispose(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
}
ToList() 方法:ToList() 时使用读锁来确保对集合进行安全的读取操作,在读取的过程中其他线程对集合的修改将会被阻塞,从而避免数据不一致的情况。ToList() 方法返回一个新的 List<T>,包含当前集合中的所有元素。此实现为 ThreadSafeObservableCollection<T> 提供了一个线程安全的 ToList() 方法,同时保留了其他基本功能的线程安全性。这样,你可以放心地在多线程环境中工作,而不必担心集合中的数据被并发修改。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
protected override void ClearItems()
{
_lock.EnterWriteLock();
try
{
base.ClearItems();
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void InsertItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index <= base.Count)
base.InsertItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void RemoveItem(int index)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.RemoveItem(index);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void SetItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.SetItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
public new T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= 0 && index < base.Count)
return base[index];
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitReadLock();
}
}
set
{
SetItem(index, value);
}
}
protected override void MoveItem(int oldIndex, int newIndex)
{
_lock.EnterWriteLock();
try
{
if (oldIndex >= 0 && newIndex >= 0 && oldIndex < base.Count && newIndex <= base.Count)
base.MoveItem(oldIndex, newIndex);
else
throw new ArgumentOutOfRangeException();
}
finally
{
_lock.ExitWriteLock();
}
}
public new bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return base.Contains(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return base.IndexOf(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
base.CopyTo(array, arrayIndex);
}
finally
{
_lock.ExitReadLock();
}
}
public new int Count
{
get
{
_lock.EnterReadLock();
try
{
return base.Count;
}
finally
{
_lock.ExitReadLock();
}
}
}
protected override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged += value;
}
finally
{
_lock.ExitWriteLock();
}
}
remove
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged -= value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (_lock.ReadLock())
{
base.OnCollectionChanged(e);
}
}
public List<T> ToList()
{
_lock.EnterReadLock();
try
{
return new List<T>(this);
}
finally
{
_lock.ExitReadLock();
}
}
public IEnumerable<T> Where(Func<T, bool> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
_lock.EnterReadLock();
try
{
return this.ToList().Where(predicate).ToList(); // Ensure snapshot and prevent lazy evaluation
}
finally
{
_lock.ExitReadLock();
}
}
public void AddRange(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items)
{
base.Add(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
public void Remove(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items.Where(i => base.Contains(i)))
{
base.Remove(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
private static class ReaderWriterLockSlimExtensions
{
public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
return new ActionOnDispose(rwLock.ExitReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterWriteLock();
return new ActionOnDispose(rwLock.ExitWriteLock);
}
private class ActionOnDispose : IDisposable
{
private readonly Action _action;
public ActionOnDispose(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
}
Where 方法说明:Where 方法中,我们通过一个读锁来确保集合在读取过程中不会被其他操作修改。List<T> 的快照,以确保结果是在锁持有期间生成,并避免 lazy evaluation(延迟执行),这可能会导致在锁释放后访问集合。通过这种方式,ThreadSafeObservableCollection<T> 提供了一个线程安全的 Where 方法,让你能安全、直观地从集合中筛选元素。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
protected override void ClearItems()
{
_lock.EnterWriteLock();
try
{
base.ClearItems();
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void InsertItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index <= base.Count)
base.InsertItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void RemoveItem(int index)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.RemoveItem(index);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
protected override void SetItem(int index, T item)
{
_lock.EnterWriteLock();
try
{
if (index >= 0 && index < base.Count)
base.SetItem(index, item);
else
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitWriteLock();
}
}
public new T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= 0 && index < base.Count)
return base[index];
throw new ArgumentOutOfRangeException(nameof(index));
}
finally
{
_lock.ExitReadLock();
}
}
set
{
SetItem(index, value);
}
}
protected override void MoveItem(int oldIndex, int newIndex)
{
_lock.EnterWriteLock();
try
{
if (oldIndex >= 0 && newIndex >= 0 && oldIndex < base.Count && newIndex <= base.Count)
base.MoveItem(oldIndex, newIndex);
else
throw new ArgumentOutOfRangeException();
}
finally
{
_lock.ExitWriteLock();
}
}
public new bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return base.Contains(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return base.IndexOf(item);
}
finally
{
_lock.ExitReadLock();
}
}
public new void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
base.CopyTo(array, arrayIndex);
}
finally
{
_lock.ExitReadLock();
}
}
public new int Count
{
get
{
_lock.EnterReadLock();
try
{
return base.Count;
}
finally
{
_lock.ExitReadLock();
}
}
}
protected override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged += value;
}
finally
{
_lock.ExitWriteLock();
}
}
remove
{
_lock.EnterWriteLock();
try
{
base.CollectionChanged -= value;
}
finally
{
_lock.ExitWriteLock();
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
using (_lock.ReadLock())
{
base.OnCollectionChanged(e);
}
}
public List<T> ToList()
{
_lock.EnterReadLock();
try
{
return new List<T>(this);
}
finally
{
_lock.ExitReadLock();
}
}
public IEnumerable<T> Where(Func<T, bool> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
_lock.EnterReadLock();
try
{
return this.ToList().Where(predicate).ToList(); // Take a snapshot and apply the predicate
}
finally
{
_lock.ExitReadLock();
}
}
public void AddRange(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items)
{
base.Add(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
public void Remove(IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
_lock.EnterWriteLock();
try
{
foreach (var item in items.Where(i => base.Contains(i)))
{
base.Remove(item);
}
}
finally
{
_lock.ExitWriteLock();
}
}
private static class ReaderWriterLockSlimExtensions
{
public static IDisposable ReadLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
return new ActionOnDispose(rwLock.ExitReadLock);
}
public static IDisposable WriteLock(this ReaderWriterLockSlim rwLock)
{
rwLock.EnterWriteLock();
return new ActionOnDispose(rwLock.ExitWriteLock);
}
private class ActionOnDispose : IDisposable
{
private readonly Action _action;
public ActionOnDispose(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
}
LockRecursionPolicy.SupportsRecursion 后,务必要确保明确的锁管理方案,确保没有潜在的死锁风险。