使用ReaderWriterLockSlim實現同步數據類:
namespace Common { public class SynchronizedWriteData<T> : IDisposable { private ReaderWriterLockSlim _dataLock = new ReaderWriterLockSlim(); private IReaderWriter<T> _innerData; private SynchronizedWriteData() { } public SynchronizedWriteData(IReaderWriter<T> innerData) { _innerData = innerData; } public T Read() { _dataLock.EnterReadLock(); try { return _innerData.Read(0); } finally { _dataLock.ExitReadLock(); } } public T Read(int argument) { _dataLock.EnterReadLock(); try { return _innerData.Read(argument); } finally { _dataLock.ExitReadLock(); } } public void Add(T instance) { _dataLock.EnterWriteLock(); try { _innerData.Write(0, instance); } finally { _dataLock.ExitWriteLock(); } } public void Add(int argument, T instance) { _dataLock.EnterWriteLock(); try { _innerData.Write(argument, instance); } finally { _dataLock.ExitWriteLock(); } } public bool AddWithTimeout(T instance, int timeout) { if (_dataLock.TryEnterWriteLock(timeout)) { try { _innerData.Write(0, instance); } finally { _dataLock.ExitWriteLock(); } return true; } else { return false; } } public bool AddWithTimeout(int argument, T instance, int timeout) { if (_dataLock.TryEnterWriteLock(timeout)) { try { _innerData.Write(argument, instance); } finally { _dataLock.ExitWriteLock(); } return true; } else { return false; } } public void Delete() { _dataLock.EnterWriteLock(); try { _innerData.Delete(0); } finally { _dataLock.ExitWriteLock(); } } public void Delete(int argument) { _dataLock.EnterWriteLock(); try { _innerData.Delete(argument); } finally { _dataLock.ExitWriteLock(); } } #region IDisposable 成員 public void Dispose() { try { _dataLock.EnterWriteLock(); { try { _innerData.Clear(); } finally { _dataLock.ExitWriteLock(); } } } finally { _dataLock.Dispose(); } } #endregion } } namespace ExternalDataHandle { /// <summary> /// 從外部數據源獲取到內部數據源的適配器抽象類 /// </summary> /// <typeparam name="T">T 數據對象類型</typeparam> public abstract class ExternalDataAdapter<T> : IDisposable { /// <summary> /// 外部數據源連接字符串 /// </summary> protected abstract string ConnectString { get; } /// <summary> /// 提供初始化數據適配器的方法 /// </summary> protected abstract void Initialize(); /// <summary> /// 提供數據傳遞的方法 /// </summary> public abstract void Transmit(); /// <summary> /// 提供從外部數據設備讀取數據的方法 /// </summary> protected abstract void ReadFromExternalDevice(); /// <summary> /// 提供保存數據到內部設備的方法 /// </summary> protected abstract void SaveToInternalDevice(); #region IDisposable 成員 public abstract void Dispose(); #endregion } }