I need to synchronize a method call, so that threads can call this method after a 500ms sleep. I have 10 threads that may run at the same time, so that simply introducing Thread.Sleep(500)
does not help. How can I achieve this in the simplest way? What can you suggest?
_pool = new Semaphore(0, 10);
_pool.Release(10);
...
pool.WaitOne();
Thread thr = new Thread(WorkerThread);
t.Start(param);
...
public static void WorkerThread(object parameterData)
{
...
MethodToBeSynced();
...
_pool.Release();
}
If you know the number of concurrent threads (And given they start approx. the same time), you could use a Barrier
with a PostPhaseAction
delegate.
var barrier = new Barrier(10, (x) => Thread.Sleep(500));
The barrier waits until 10 threads are at a certain code point and once that happens, each thread will sleep for 500 ms and then continues.
If the exact number of threads is unknown, you could specify a wait timeout to not block infinite.
// Waits up until N threads are at the barrier or after the timeout has elapsed.
_barrier.SignalAndWait(500);