-
Notifications
You must be signed in to change notification settings - Fork 1
05. ThreadSafe
ThreadSafe<T> is a special wrapper instance type that can make any other type thread-safe to be used in concurrency.
It works by having a lock and limiting modification access to a single thread at a time.
You can access the value any time by using ThreadSafe.Value.
and modify the value using two functions
public T Modify(Func<T, T> modificationFunc)This both modifies the value and returns the result after modification.
or
public T Modify(IModifier<T> modifier, T newValue)This works similarly to the previous but uses a special IModifier<T> interface to reduce the memory allocation of the lambda/delegate.
This interface will be explained using an example, lets say that we want the value to be counter, but used in parallel,
public class Adder : IModifier<int> {
public int Modify(int value, int newValue) {
return value + newValue;
}
}Then we can use this together with a ThreadSafe<int> value to modify it.
ThreadSafe<int> counter = new(0); // Initialize the counter
// Imagine we are inside another function that is executed in parallel
var modifier = new Adder(); // you can make this a readonly property or field to reduce memory allocations
var updated = counter.Modify(modifier, 1); // this will increment the value of the counter by 1 and return the result.Using ThreadSafe<T> requires much less overhead than using a certain element of a concurrent collection to maintain a thread-safe value.