Wednesday, June 13, 2012

Synchronous call using Delegates in C#


In this post Synchronous call using Delegates in C#, we shall see on how to use delegates as reference to functions and make a Synchronous call to the references function.

Delegates in c# act as function pointers to functions, they can refer to any function which has the same signature as the delegate. To know more about the basics of Delegates refer to the post Delegates in C#.

Here we shall see on how Delegates can be used to make synchronous calls to the references function, when we make a synchronous call the calling thread waits for the referenced function to complete its execution, till the references function is executed the User Interface is locked and the users will not be allowed to perform any other operation.

Let us try to use Delegates to populate a DataGridView with data, the Delegate will be mapped to a function in the Domain class clsEmployee and a Synchronous call is made to the mapped function to populate the DataGridView.

First let us create a Domain layer class clsEmployee, and add a method GetEmployeeList  
to this class, our delegate will be mapped to this method to get the details.

class clsEmployee
{
    public DataTable GetEmployeeList(int DepartmentID)
    {
        // Read the connection string from the app.config file.
        string strConn = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
        SqlConnection objConn = new SqlConnection(strConn);
        SqlCommand objCmd = new SqlCommand("SELECT * FROM EMPLOYEE WHERE DepartmentID = " + DepartmentID, objConn);
        SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
        DataSet dsEmployee = new DataSet();
        //
        objDA.Fill(dsEmployee, "dtEmployee");
        //
        System.Threading.Thread.Sleep(5000);
        return dsEmployee.Tables["dtEmployee"];
    }
}

Fine, now we will move to the From End code, declare the delegate and map it to the above method.

Declare the Delegate
delegate DataTable GetEmployeeListDelegate(int intDepartmentID);


Initialize the delegate and map it to the function in the Domain class.
DataTable dtEmployees;
clsEmployee objEmployee = new clsEmployee();
delegate_GetEmployees = new GetEmployeeListDelegate(objEmployee.GetEmployeeList);
dtEmployees = delegate_GetEmployees(Convert.ToInt16(cmbDepartment.SelectedValue));
//
gvEmployees.DataSource = dtEmployees;

Here the Delegate in initialized and mapped to the function in the line
delegate_GetEmployees = new GetEmployeeListDelegate(objEmployee.GetEmployeeList);

The call to the mapped function is made indirectly by invoking the delegate in the line
dtEmployees = delegate_GetEmployees(Convert.ToInt16(cmbDepartment.SelectedValue));

When this like gets executed, the mapped function is called through the delegate and the DataTable with the details is passed to the UI layer through the delegate.

Remember we are making a Synchronous call with the delegate hence, the User Interface will be locked, till the time the function called through the delegate completes its execution.
Once the execution in over, the DataTable is bound to the GridView to display the data.

The Complete code is as follows

Domain Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WinApp
{
    class clsEmployee
    {
        public DataTable GetEmployeeList(int DepartmentID)
        {
            // Read the connection string from the app.config file.
            string strConn = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
            SqlConnection objConn = new SqlConnection(strConn);
            SqlCommand objCmd = new SqlCommand("SELECT * FROM EMPLOYEE WHERE DepartmentID = " + DepartmentID, objConn);
            SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
            DataSet dsEmployee = new DataSet();
            //
            objDA.Fill(dsEmployee, "dtEmployee");
            //
            System.Threading.Thread.Sleep(5000);
            return dsEmployee.Tables["dtEmployee"];
        }
    }
}

UI Windows Form code
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;
using System.Configuration;
using System.Data.SqlClient;

namespace WinApp
{
    delegate DataTable GetEmployeeListDelegate(int intDepartmentID);
    //
    public partial class frmViewEmployees : Form
    {
        GetEmployeeListDelegate delegate_GetEmployees;
        //
        private void btnLoadEmployees_Click(object sender, EventArgs e)
        {
            DataTable dtEmployees;
            clsEmployee objEmployee = new clsEmployee();
            delegate_GetEmployees = new GetEmployeeListDelegate(objEmployee.GetEmployeeList);
            dtEmployees = delegate_GetEmployees(Convert.ToInt16(cmbDepartment.SelectedValue));
            //
            gvEmployees.DataSource = dtEmployees;
        }
        //
        public frmViewEmployees()
        {
            InitializeComponent();
        }
        //

        private void frmViewEmployees_Load(object sender, EventArgs e)
        {
            BindDepartments();
        }
        //
        private void BindDepartments()
        {
            // Read the connection string from the app.config file.
            string strConn = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
            SqlConnection objConn = new SqlConnection(strConn);
            SqlCommand objCmd = new SqlCommand("SELECT 0 as ID,'-Select-' as Name UNION SELECT ID, NAME FROM DEPARTMENT", objConn);
            SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
            DataSet dsDepartment = new DataSet();
            //
            objDA.Fill(dsDepartment, "dtDepartment");
            //
            cmbDepartment.DataSource = dsDepartment.Tables["dtDepartment"];
            cmbDepartment.DisplayMember = "Name";
            cmbDepartment.ValueMember = "ID";
        }
    }
}



Search Flipkart Products:
Flipkart.com

No comments: