Home > Development > Fork Join Parallelism with CountDownEvent

Fork Join Parallelism with CountDownEvent


Here is a classic example of Fork-Join Parallelism with CountDownEvent. You define how many thread are going to be doing work in the constructor, in this case four. The when each thread finished work call Signal which decrements the counter. When you call Wait() it blocks until the count is zero.

Easy hey.

 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TPLSamples
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.TestingCountdownEvent();

            Console.WriteLine("Press any key to quit...");
            Console.ReadKey();
        }

        public void TestingCountdownEvent()
        {

            CountdownEvent @event = new CountdownEvent(4);

            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(2200);
                Console.WriteLine("Doing Something In First Call");
                @event.Signal();
            });

            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(2200);
                Console.WriteLine("Doing Something In Second Call");
                @event.Signal();
            });

            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(2200);
                Console.WriteLine("Doing Something In Third Call");
                @event.Signal();
            });

            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(2200);
                Console.WriteLine("Doing Something In Forth Call");
                @event.Signal();
            });

            @event.Wait();
            Console.WriteLine("Finished tasks....");
        }
    }
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: