Last active
December 10, 2019 19:34
-
-
Save YairHalberstadt/b5653c21c5e207b4c79501d1fef979c0 to your computer and use it in GitHub Desktop.
AtomicReference In C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class AtomicReference<T> | |
{ | |
private object _lock = new object(); | |
private T _value; | |
public AtomicReference(T value) => _value = value; | |
public void LockedUpdate(Func<T,T> updateFunc) | |
{ | |
lock(_lock) | |
{ | |
_value = updateFunc(_value); | |
} | |
} | |
public void LockedAccess(Action<T> action) | |
{ | |
lock(_lock) | |
{ | |
action(_value); | |
} | |
} | |
public TResult LockedAccess<TResult>(Func<T, TResult> accessAndReturnResult) | |
{ | |
lock(_lock) | |
{ | |
return accessAndReturnResult(_value); | |
} | |
} | |
public TResult LockedAccessAndUpdate<TResult>(Func<T, (T, TResult)> accessAndUpdate) | |
{ | |
lock(_lock) | |
{ | |
TResult result; | |
(_value, result) = accessAndUpdate(_value); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment