C# Latch implementation

This is a c# Latch implementation for multithreaded applications (equivalent to java CountDownLatch).

It’s used in a situation when you have a one thread waiting for a number of other threads to finish.

The Test below also uses a Semaphore to run only a specific number of child threads at one time.

public class Latch
{
private readonly object locker = new object();
private int count;

public Latch(int noThreads)
{
lock (locker)
{
count = noThreads;
}
}

public void Await()
{
lock (locker)
{
while (count > 0)
{
Monitor.Wait(locker);
}
}
}

public void CountDown()
{
lock (locker)
{
if (--count <= 0)
{
Monitor.PulseAll(locker);
}
}
}

public int GetCount()
{
lock (locker)
{
return count;
}
}
}

[TestFixture]
public class TestLatch
{
static Latch latch = new Latch(5);
private Random random = new Random();
static Semaphore semaphore = new Semaphore(3,3);

public void Test()
{
for(int i=0;i<5;i++)
{
new Thread(RunIt).Start();
}
Console.WriteLine("Waiting for all threads to finish..");
latch.Await();
Console.WriteLine("All Threads completed.");
}

public void RunIt()
{
semaphore.WaitOne();
int waitTime = random.Next(5000);
Console.WriteLine("Running job {0}", waitTime);
Thread.Sleep(waitTime);
Console.WriteLine("Completed.");
semaphore.Release();
latch.CountDown();
}
}

Comments

Popular posts from this blog

Parse XML to dynamic object in C#

C# Updating GUI from different thread