Posts tagged: delegate

Different ways to use Delegates

By Ashish Khandelwal, July 6, 2010

Here is the example covers all different ways to use the delegate – Just copy and paste the code:

  1. How to use Delegate
  2. How to use Multicast Delegate
  3. How to Call specific method from Multicast Delegate with executing in given Sequence
  4. How to call Delegate Asynchronously
  5. How to use Event


using System;
using System.Collections;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{

public class Book
{
public string Name { get; set; }
public decimal Price { get; set; }
public Book(string Name, decimal Price)
{
this.Name = Name;
this.Price = Price;
}
}
public delegate void ProcessBookDelegate(Book bk);

public class Stock
{
public ArrayList Books = new ArrayList();
public delegate void NewBookAddedHandler(Book newbook);
public event NewBookAddedHandler NewBookAdded;
public void AddBook(string Name, decimal Price)
{
Book bk = new Book(Name,Price);
Books.Add(bk);

if (NewBookAdded != null)
NewBookAdded(bk);
}
public void ProcessBook(ProcessBookDelegate dele)
{
foreach (Book item in Books)
{
dele(item);
}
}
}
public class TotalStock
{
int NumberOfBooks ;
decimal TotalAmount ;

public void AddTotalToCount(Book bk)
{
NumberOfBooks++;
TotalAmount += bk.Price;
}
public void ShowTotal()
{
Console.WriteLine(NumberOfBooks.ToString() + " " + TotalAmount.ToString());
}
}
class Program
{
static void PrintBookTitalAndPrice(Book bk)
{
Console.WriteLine(bk.Name + " " + bk.Price.ToString());
}
static void PrintBookTital(Book bk)
{
Console.WriteLine(bk.Name );
}
static void Main(string[] args)
{

Stock bookstock = new Stock();
bookstock.NewBookAdded += new Stock.NewBookAddedHandler(bookstock_NewBookAdded);
bookstock.AddBook("ABC", 9);
bookstock.AddBook("ABC1", 19);
bookstock.AddBook("ABC2", 29);
bookstock.AddBook("ABC3", 39);
bookstock.AddBook("ABC4", 49);

TotalStock tstk = new TotalStock();

// Multicast delegate
ProcessBookDelegate pbd = new ProcessBookDelegate(tstk.AddTotalToCount);
pbd += new ProcessBookDelegate(PrintBookTitalAndPrice);
pbd += new ProcessBookDelegate(PrintBookTital);
bookstock.ProcessBook(pbd);

// Do not want to call the methods in the same sequance they are registered
// call the method without sequance
Delegate[] del = pbd.GetInvocationList();
del[2].DynamicInvoke(new Book("a", 9));

// Asyncronous Calling of delegate
ProcessBookDelegate pbd1 = new ProcessBookDelegate(tstk.AddTotalToCount);
// 1st way - without any endinvoide handler
IAsyncResult result = pbd1.BeginInvoke(new Book("b", 2), null, null);
pbd1.EndInvoke(result); // the end invoke will exceute once the delete call finishes

// 2nd way - without handleer but use the iscompareled to check the status
IAsyncResult result1 = pbd1.BeginInvoke(new Book("b", 2), null, null);
while(!result1.IsCompleted)
{
Thread.Sleep(100);
}
pbd1.EndInvoke(result1); // the end invoke will exceute once the delete call finishes

// 3rd way - without handler but use waitone to get tigger to the current thread
IAsyncResult result2 = pbd1.BeginInvoke(new Book("b", 2), null, null);
result2.AsyncWaitHandle.WaitOne();
pbd1.EndInvoke(result2); // the end invoke will exceute once the delete call finishes

// 4th way - with callback handler
pbd1.BeginInvoke(new Book("b", 2), new AsyncCallback(CallBack), pbd1);

Console.WriteLine("Press Enter to see total.");

Console.ReadLine();
tstk.ShowTotal();
Console.ReadLine();
}

static void bookstock_NewBookAdded(Book newbook)
{
Console.WriteLine("New Book Added: " + newbook.Name);
}

static void CallBack(IAsyncResult result)
{
ProcessBookDelegate pbd1 = (ProcessBookDelegate) result.AsyncState;

pbd1.EndInvoke(result);

Console.WriteLine("CallBack ended.");
}

}

}

VN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)

The dark side of C# Delegates

By Ashish Khandelwal, October 25, 2009

This article assumes basic programming experience with delegates.

Delegates are a .NET framework feature that allows for type-safe function pointers. Actually, they are a bit more than function pointers, because they are object oriented, as their second name -bound method references- expresses. It means that the method pointer stored in the delegate may actually be bound to an instance of a specific object: when the delegate is invoked, the method is called on that target object. In the code of that method, you can notice that the this variable refers to that same target object.
But as we’ll also see, delegates aren’t always bound to an object. They support storing a static method pointer, which isn’t bound to any specific instance of the class, like classic C-style function pointers. Read more »

VN:F [1.7.2_963]
Rating: 5.0/5 (1 vote cast)

Events Programming in C# and .NET

By Ashish Khandelwal, October 25, 2009

In the early days of computing, a program would begin execution and then proceed through its steps until it completed. If the user was involved, the interaction was strictly controlled and limited to filling in fields.

Today’s Graphical User Interface (GUI) programming model requires a different approach, known as event-driven programming. A modern program presents the user interface and waits for the user to take an action. The user might take many different actions, such as choosing among menu selections, pushing buttons, updating text fields, clicking icons, and so forth. Each action causes an event to be raised. Other events can be raised without direct user action, such as events that correspond to timer ticks of the internal clock, email being received, file-copy operations completing, etc. In programming, you are often faced with situations where you need to execute a particular action, but you don’t know in advance which method, or even which object, you’ll want to call upon to execute it. For example, a button might know that it must notify some object when it is pushed, but it might not know which object or objects need to be notified.

C# adds on value to the often mentioned world of event driven programming by adding support through events and delegates. Read more »

VN:F [1.7.2_963]
Rating: 4.0/5 (1 vote cast)