I want to call a Action every X cycles (in my case: to a transaction commit every 100 records). So i do:
public class CyclicActionCaller
{
private int _counter;
private int _cycleValue;
private Action _methodToCall;
public CyclicActionCaller()
{
_counter = 0;
}
public CyclicActionCaller Every(int cycleValue)
{
_cycleValue = cycleValue;
return this;
}
public CyclicActionCaller Call(Action methodToCall)
{
_methodToCall = methodToCall;
return this;
}
public void PerformCall()
{
Interlocked.Increment(ref _counter);
// IS THIS THREAD SAFE - SHOULD BE CALLED EVERY _counter % _cycleValue - EVEN IN MULTITHREADING ENVIRONMENT
if (_counter % _cycleValue == 0)
{
_methodToCall();
}
}
}
CyclicActionCaller cyclicActionCaller = new CyclicActionCaller();
using (ModelContainer container = new ModelContainer())
{
cyclicActionCaller.Every(100).Call(() => { container.SaveChanges(); });
while(...) { // Import Loop - assume multiple workers inside
cyclicActionCaller.PerformCall(); // every worker calls this after inserting a row
}
}
Is this function thread safe? I want that - even if multiple threads call PerformCall - that it is just called once every 100 calls
Best regards