You sometimes need to send a progress report to the user on the status of a particular function. Ex. when inserting records etc.
// FROM YOUR FORM
private void button1_Click(object sender, EventArgs e)
{
yourclass.updatedb({"One","Two","Three"},this.ProgressBar1)
}
// INSIDE YOUR CLASS
public string updatedb(string[] values,System.Windows.Forms.Progressbar pb)
pb.Maximum = values.Length();
foreach(string v in values)
_insertdb(v); // CALL THE UPATE DB METHOD
pb.Value ++;
Essentially delegates are function pointers (which is a concept used in languages like C/C++). They are also a class in the .net programming framework (System.Delegate). It is an abstract class and its sealed; meaning you cannot inherit it. Delegates are object oriented, type-safe and secure.
Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.
Asynchronous patterns of code execution mainly employ the callback pattern. The callback function will execute once the asynchronous task completes. Developers mainly utilize this idea so that the end-users get the benefit of executing a followup routine (post asynchronous operation), but the developer need not know what that routine is or what it does. However the developer has to ensure that that routine (which is a method) has a signature that the end users specify.
Take the example of the FileStream class in the System.IO namespace. It is mainly used for I/O. It has methods like BeginRead() and BeginWrite(); they are asynchronous versions of Read() and Write() respectively. They execute on a different thread.
If you examine the prototype of the first method you would find the third argument (AsyncCallback userCallback) is actually a delegate. And, it expects a method whose return type is void and takes one argument of type IAsyncResult.
public override System.IAsyncResult BeginRead(byte[ ] array, int offset, int numBytes, System.AsyncCallback userCallback, object stateObject)
The declaration for AsyncCallback is:
public delegate void AsyncCallback(System.IAsyncResult ar)
The BeginRead() method returns a value of type IAsyncResult. If you want to wait for an asynchronous read-operation to end, you have to call EndRead() and pass the corresponding IAsyncResult value.
On a general note those classes which do some operation asynchronously have their corresponding Begin and End methods. Keep exploring to find out.
Happy programming. (and a happy new 2009). ;)