-
Notifications
You must be signed in to change notification settings - Fork 0
Semaphore factory
The semaphore factory was created to allow operations that might need to lock object a simple and unit testable way to get a lock on a specific object.
Although it's called a semaphore factory you are not restricted to using a semaphore although the returned value from the factory will have to be an ISemaphore.
To override the default semaphore factory you will need to create a class that inherits ISemaphoreFactory.
The ISemaphoreFactory interface only has one method which is create.
The create method returns an ISemaphore and takes in an initial count and a max count. Initial count is intended to specify how many locks are available right now to be placed on an specific data object at once. The max count is intended to specify how many total locks can be placed on a data object at once.
ISemaphore Create(int initialCount, int maxCount);
This interface allow a lock to be created (wait) and removed (release). ISemaphore is used to allow unit testing of the workers to be possiable.
A call to wait is intened to course a lock to be put on the object the lock is for. If the max number of locks are taken the wait method might not return until the lock can be placed.
bool Wait(TimeSpan timeout);
Returns true if the lock is applied and false if it couldn't or the timeout elapsed. The timeout is used to specifiy how long to wait before giving up when trying to apply a lock.
A call to release should remove a lock from the object that is locked
int Release();
Returns how many locks where on the object.
The factory is intended to be used by workers that wish to lock a resource while working on it. For example if using the file system to store data the worker might want to get a lock for the file and have other operations carried out on that object delayed until the file is saved back to the file system.
The default Semaphore factory uses a SemaphoreProxy which is a SemaphoreSlim with the interface ISemaphore. SemaphoreSlim is part of the System.Threading namespace and is a nice simple semaphore to use.
If your storage system already provides enough locking then you might not need a semaphore factory or you might want to work out if you can use the semaphore factory to work between your storage system and the workers however you don't have to have a semaphore factory if you don't need one.