Friday, July 12, 2013

Simple delegate example




C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

The below example will explain the delegate easily. In the button event I have declared the delegate methods and called two different methods. In the run time the two methods will run in simultaneously. After completed the long loop in the message box will give you the message the methods completed.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public delegate string dgMethod();
        public delegate int dgAddMethod();

        private void Form1_Load(object sender, EventArgs e)
        {          

        }        
        public string strName()
        {
            for (int i = 0; i < 1000000000; i++)
            {                
            }
            MessageBox.Show("strName methods");
            return "vijay";
        } 
        public int iADD()
        {
            for (int i = 0; i < 1000000000; i++)
            { 
            }
            MessageBox.Show("ADD Method");
            return 9;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string strEndinvoke = string.Empty;
            int iEndinvoke = 0;

            dgMethod objStrName = new dgMethod(strName);
            dgAddMethod objAdd = new dgAddMethod(iADD);

            IAsyncResult iStrName = null;
            IAsyncResult iAdd = null;

            iStrName = objStrName.BeginInvoke(nullnull);
            iAdd = objAdd.BeginInvoke(nullnull);

            //strEndinvoke = objStrName.EndInvoke(iStrName);
            //iEndinvoke = objAdd.EndInvoke(iAdd);

            label1.Text = strEndinvoke;
            label2.Text = iEndinvoke.ToString();
        }        
    }
}

No comments: