Friday, January 14, 2011

Using Multicast Delegate in console application.

A multicast delegate derives from the System.MulticastDelegate class. It contains an invocation list of multiple methods. In multicasting you create a single delegate that invokes multiple encapsulated methods. You need to ensure the return type of all these delegates is same.
Consider the coffee vending machine example. You are dispensing black coffee, which in turn call the methods to dispense hot water and coffee powder. If you want the methods to dispense hot water and coffee powder to be called at same time, you can make use of a multicast delegate.
Multicast delegate hold the reference of more than one method therefore, if you call a multicast delegate it will execute all the method it wraps in the calling order. The multiple method call by the delegate in this case should not return any value because several multicast delegate are called consecutively and you cannot wait to get the return value from each of these methods.

The following example shows how to use a multicast delegate:
using System;
using System.IO;

// program to write the data to the console and file

namespace delegate2
    public class PrintToDevice
        //creating the variables of stream class
        static FileStream FStream;
        static StreamWriter SWriter;

        //Defining a Delegate

        public delegate void PrintData(string s);

        //Method to print a string to the console
        public static void WriteConsole(string str)
            Console.WriteLine("{0} console", str);

        // Method to print a string to a file
        public static void WriteFile(string s)
            //initializing stream object

            FStream = new FileStream("c:\\StoreData.txt", FileMode.Append, FileAccess.Write);

            SWriter = new StreamWriter(FStream);
            s = s + "File";

            //writing a string to the file

            //removing the content from the buffer

        //Method to send the string data to respective methods

        public static void Displaydata(PrintData pmethod)
            pmethod("this should go to the");

        public static void Main()
            //initializing the delegate object
            PrintData MlDelegate = new PrintData(WriteConsole);
            MlDelegate += new PrintData(WriteFile);
            MlDelegate -= new PrintData(WriteFile);


Note:- Considers a situation where all the methods are called at the same instance. Using the same delegate, multicasting helps to call both the WriteFile ( ) method and the WriteConsole ( ) method in one call. MIDelegate holds reference of both the WriteConsole ( ) and WriteFile ( ) methods.

No comments:

Recent Posts