CSharp - Multicast delegate example

Introduction

The following code use delegate to implement an progress call back.

The call back is used as a reporter to display the current progress.

Demo

using System;
delegate void ProgressReporter(int percentComplete);

class Test/*from w w  w . j  av a  2  s .  co  m*/
{
    static void Main()
    {
        ProgressReporter p = WriteProgressToConsole;
        p += WriteProgressToFile;
        HardWork(p);
    }

    static void WriteProgressToConsole(int percentComplete)
      => Console.WriteLine(percentComplete);

    static void WriteProgressToFile(int percentComplete)
      => System.IO.File.WriteAllText("progress.txt",
                                       percentComplete.ToString());

    static void HardWork(ProgressReporter p)
    {
        for (int i = 0; i < 10; i++)
        {
            p(i * 10);                           // Invoke delegate
            System.Threading.Thread.Sleep(100);  // Simulate hard work
        }
    }

}

Result

Related Topic