Skip to content

Instantly share code, notes, and snippets.

@kleinron
Created May 12, 2023 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kleinron/0a6afd3ebbbcc4b966ce24a5d3d8114b to your computer and use it in GitHub Desktop.
Save kleinron/0a6afd3ebbbcc4b966ce24a5d3d8114b to your computer and use it in GitHub Desktop.
using System.Threading;
namespace Pepperoni.Lib
{
public class SafeValueSeldomWrites<T>
{
private T innerValue;
private readonly ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
public SafeValueSeldomWrites()
{
}
public SafeValueSeldomWrites(T initialValue)
{
innerValue = initialValue;
}
public T Value
{
get
{
locker.EnterReadLock();
try
{
T result = innerValue;
return result;
}
finally
{
locker.ExitReadLock();
}
}
set
{
locker.EnterWriteLock();
try
{
innerValue = value;
}
finally
{
locker.ExitWriteLock();
}
}
}
}
}
namespace Pepperoni.Lib
{
public class SafeValue<T>
{
private readonly object locker = new object();
private T innerValue;
public SafeValue()
{
}
public SafeValue(T initialValue)
{
innerValue = initialValue;
}
public T Value
{
get
{
lock (locker)
{
return innerValue;
}
}
set
{
lock (locker)
{
innerValue = value;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment