Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Working with Delegates -Part II

Working with Delegates -Part II

In this article we will discuss about delegates, what is multicast delegates and its contribution in Asynchronous communications and also how to work with long-running processes etc.

Total page views :  4353
Total downloads :  131
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DelegatesSample.zip
 
Become a Sponsor

In the previous session we have discussed about delegates and its basic features. Now I would like to introduce some of the interesting features of Delegates.
 
Multicast delegates

As we have discussed in the earlier session, delegates represents functional pointers. When a delegate represents multiple methods, it is multi cast delegates.
 
Multicast delegates should represent void methods. By adding += I am making this delegate to multicast. The moment I add this += it becomes an array !. This would hold as many numbers of methods as you specify.

// Normal delegate
Calculator c = new Calculator();
BusinessControl bc = new BusinessControl();
CalculatorHandler ch = new CalculatorHandler(c.Add);
MessageBox.Show(bc.CallMe(ch).ToString()); 
//call add method - > this technique is called IOC           
// multi cast delegate
Calculator c = new Calculator();
BusinessControl bc = new BusinessControl();
CalculatorHandler ch = new CalculatorHandler(c.Add);
ch += new CalculatorHandler(c.Add);
ch += new CalculatorHandler(c.Multiply);
MessageBox.Show(bc.CallMe(ch).ToString());

Here is how it works. When you invoke the delegate, 'Add' method will be called first followed by 'Multiply' in a single thread and the compiler will come back to you once it is done with all methods specified in the multicast delegate.
 
Note that you will get a response back only after completing both the tasks ie. Add and Multiply. This is the reason it is suggested that Multicast delegates should represent only void methods.
 
Hope this might have given you an idea of multicast delegates.  Let us look at what is Synchronized and Asynchronized communications and how delegates support these features.
 
Synchronized Communication

In our previous example, when we call Add() method of calculator class, using oCalc.Add(), we are making a synchronized communication. Meaning, we are waiting for Calculator object to complete its Add method.  To test this, add a Thread.Sleep(10000) in the add method. When we call this method, the current thread will be in sleep mode for 10000 milliseconds. In other words, we are forced to wait until the compiler is done with the Add method.

public
int Add(int a, int b)
{
    Thread.Sleep(10000);
    Console.WriteLine((a + b).ToString());
    return (a + b);
}

It is not possible to call any other method untill 10000 ms is completed. This is called synchronous communication.
 
Practical implementation: Think of a complex stored-procedure that takes 10000 ms to execute. We cannot proceed with next step until the procedure is completed and the compiler gets back to the code.

Asynchronous Communication
 
Asynchronous methods will not wait for the completion of current thread, and hence we can proceed with next.
 
This is something like we delegate the work to a third person to do the task on our behalf.

Having said this, how about getting a notification from that person once he completes the tasks?  Sounds good isn't it? We will discuss about this later.
 
To try asynchronous methods, we are adding Thread.Sleep(10000) to both Add() and Multiple() methods of Calculator class. This is nothing but to demonstrate the waiting period. Please refer to the below sections.

Synchronize Call - Normal

Calculator c = new Calculator();
BusinessControl bc = new BusinessControl();
CalculatorHandler ch = new CalculatorHandler(c.Add);
MessageBox.Show(bc.CallMe(ch).ToString());
 
You will notice that, until it is completed we won't be able to do any other task and the entire application would be locked. Try typing something in the textbox during this invocation.
 
Converting to Asynchronize Call

Calculator
c = new Calculator();
CalculatorHandler ch = new CalculatorHandler(c.Add);
ch.BeginInvoke(100, 25, null, null);

ch = new CalculatorHandler(c.Multiply);           
ch.BeginInvoke(25, 4, null, null);
 
Now type something in a textbox.
 
What is Begin Invoke

The moment you call BeginInvoke, you are creating a fork.  Meaning, each delegate will be executed in different threads through BeginInvoke. 
 
The current thread will be splitted into three. One will represent the main thread from which the delegates are called, one will go for the C.ADD method and the other one will be used for the C.MULTIPLY method.
 
What is End Invoke
 
EndInvoke is nothing but just opposite action of BeginInvoke. This will create a Join ie, it will wait for all other threads to complete and combine them all together into one single thread and proceed with the Main thread.
 
Getting results from Asynchronous call - Long running processes

Here I would like to introduce a new member IAsynchResult interface. It takes responsibility to get the work done by the delegate and bring the result back to your location.  IAsynchResult.IsCompleted returns true when the asynchronous job is completed; until that time it is false and you can continue with your work. Hence we can use this to assess whether the long running process is completed.

private
void button4_Click(object sender, EventArgs e)
{
    Int32 intResult;
    Calculator c = new Calculator();
    CalculatorHandler ch = new CalculatorHandler(c.Add);
    IAsyncResult ar1 = ch.BeginInvoke(100, 25, null, null);
   
int Counter = 0;
    while (!ar1.IsCompleted)
    {
        // Do other stuffs
        Counter++;
    }
    // Now we know that call is completed as IsCompleted has returned true
    textBox1.Text = Counter.ToString() + " times i was doing my other work";
    intResult = (int)ch.EndInvoke(ar1);
    MessageBox.Show(intResult.ToString());
}
 
Now what about Out parameters?
 
So how are we supposed to deal with out parameters of our method?  Let us take a look at the Add method which takes a parameter int as Out. Here's how it goes,
 
Int Add(Int,int,out int).   
 
Then use,
BeginInvoke(int,int,null,null) and the EndInvoke will be EndInvoke(out int).
 
Call Back Mechanism - Completion Notification

The idea is to make the calculator come back and say I have finished my work and this is the result. This mechanism is called Callback.
 
So far, the last two parameters of BeginInvoke have been passed as null. What was that all about? Is that the one that makes delegates responsive? 

Yes, we will discuss this in next part. Mark your suggestions and comments


Login to add your contents and source code to this article
 About the author
 
Santhosh Veeraraman LnT
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DelegatesSample.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.