Write a Cooperative Algorithm - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Write a Cooperative Algorithm

Demo Code


using System;// ww w  .  java  2  s.  c  o  m
using System.Threading;
using System.Threading.Tasks;

class MainClass
    {
        static void Main(string[] args)
        {
            Barrier myBarrier = new Barrier(3, (barrier) => notifyPhaseEnd(barrier));

            Task task1 = Task.Factory.StartNew(() => cooperatingAlgorithm(1, myBarrier));
            Task task2 = Task.Factory.StartNew(() => cooperatingAlgorithm(2, myBarrier));
            Task task3 = Task.Factory.StartNew(() => cooperatingAlgorithm(3, myBarrier));

            Task.WaitAll(task1, task2, task3);

            Console.WriteLine("\nMain method complete. Press Enter");
            Console.ReadLine();
        }

        static void cooperatingAlgorithm(int taskid, Barrier barrier)
        {
            Console.WriteLine("Running algorithm for task {0}", taskid);

            performPhase1(taskid);
            barrier.SignalAndWait();

            performPhase2(taskid);
            barrier.SignalAndWait();
        }

        static void performPhase1(int taskid)
        {
            Console.WriteLine("Phase one performed for task {0}", taskid);
        }

        static void performPhase2(int taskid)
        {
            Console.WriteLine("Phase two performed for task {0}", taskid);
        }

        static void notifyPhaseEnd(Barrier barrier)
        {
            Console.WriteLine("Phase has concluded");
        }
    }

Result


Related Tutorials