I wrote the following class so that a single object can be shared across many threads. Is using the ReaderWriterLockSlim
redundant in this case and only Interlocked.Funcs()
can do the job and ensure thread safety?
using System.Threading;
public class SharedData<T> where T:class
{
T _data;
ReaderWriterLockSlim _lock;
public SharedData(T arg)
{
Interlocked.Exchange<T>(ref _data, arg);
_lock = new ReaderWriterLockSlim();
}
public T Value
{
get
{
_lock.EnterReadLock();
var ret = Interlocked.CompareExchange<T>(ref _data, default(T), default(T));
_lock.ExitReadLock();
return ret;
}
set
{
_lock.EnterWriteLock();
Interlocked.Exchange<T>(ref _data, value);
_lock.ExitWriteLock();
}
}
}
ReaderWriterLockSlim
isIDisposable
which ironically makes it not thread-safe, since disposing it when there are pending readers/writers throws an exception. \$\endgroup\$