tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

CountdownEvent example

10 Jun 2009 .NET, Multithreading/Parallelism/Asynchronous/Concurrency

Yesterday I wrote about new CountdownEvent class. But what’s better than see some example of usage? ;-)

Below is pretty simple example of usage. You can see, it’s very similar to work with array of i.e. ManualResetEvent. But you have also some handy methods and properties. For instance: AddCount/TryAddCount or CurrentCount. Very handy.

class Program
{
		static void Main(string[] args)
		{
				using (CountdownEvent cde = new CountdownEvent(10))
				{
					for (int i = 0; i < cde.InitialCount; i++)
					{
							new Thread(new ParameterizedThreadStart(Dummy)).Start(cde);
							//ThreadPool.QueueUserWorkItem(new WaitCallback(Dummy), cde);
					}
					cde.Wait(2000);
					Console.WriteLine("Threads done in first 2 seconds: {0}.", cde.InitialCount - cde.CurrentCount);
					cde.Wait();
					Console.WriteLine("All threads done.");
				}
		}
		static void Dummy(object o)
		{
				Thread.Sleep(new Random().Next(5000));
				(o as CountdownEvent).Signal();
		}
}

As I said, the work is similar to work with array of ManualResetEvent, just packed into nicer cake. In fact, if you start ILDasm and look into the code you’ll see, that’s implemented very similarly. It’s using ManualResetEventSlim (also new in .NET 4) internally to signal and smart work with Interlocked class do decrement (or increment) the number of signals received.

Do you like the class too?