Firing Delegates Asynchronously


One of the most powerful features of delegates is the ability to invoke the function the delegate stores asynchronously. Executing the function asynchronously means that the system invokes the method in another thread and execution returns to the main thread immediately, before the method is done executing.

A thread is an operating system object that determines the sequence of functions that the processor will execute. What happens is that the operating system gives each thread a certain amount of time to execute some code. Even before the code is done executing, the OS may decide to halt a thread to give another thread a chance to execute.

When you execute a function asynchronously, the .NET framework allocates a pool of threads. It then takes one of the threads from the pool and uses it to execute the function. This leaves the main thread free to continue executing its code. There are two ways to execute a delegate asynchronously. One is to execute the delegate asynchronously, and then write code that waits until the delegate is done executing. The second approach is to let the system inform you when it is done by providing the system with a function in your class that it can call when it is done executing the function asynchronously.

To execute a delegate function asynchronously and wait:

  1. Type IAsyncResult rs1 , where rs1 is any variable name .

  2. Type an equal sign = .

  3. Type del.BeginInvoke where del is the name of a variable that stores a delegate function.

  4. Type an open parenthesis ( .

  5. Type the parameters for the delegate function.

  6. Type ,null , null after the last parameter of the delegate function.

  7. Type a close parenthesis ) .

  8. Type a semicolon ; .

  9. For instructions on how to wait for the delegate to complete, read the section "Waiting for Asynchronous Delegates to Complete," later in this chapter ( Figure 10.16 ).

    Figure 10.16 Remember that delegate classes have an Invoke method. This method is what gets called if you use the delegate variable directly followed by parenthesis and the parameters. BeginInvoke executes the same function, but asynchronously.
     class Tasks {    public bool Task1(string desc)    {       return true;    }    public static bool Task2(string desc)    {       return true;    } } delegate bool TaskDel(string desc); public class WebForm1 : System.Web.UI.Page {    private void Page_Load(object sender,                 System.EventArgs e)    {       TaskDel del1 =       new TaskDel(Tasks.Task2);  IAsyncResult rs =   del1.BeginInvoke(   "Calling Task1...",null,null);  } } 

To execute a delegate function asynchronously and let the system tell you when it is done:

  1. Declare a function in your class that will be used for the system to notify you when the delegate is done executing. The function should have the following prototype:

     public void FunctionDone ( IAsyncResult ar) { } 

    You can use any function name you like as long as you match the parameters.

  2. Type AsyncCallback cb = new AsyncCallback(this.FunctionDone); where cb is any variable name to store a delegate to the function that the system will use to notify you when it is done, and FunctionDone is the name of the function you declared in step 1.

  3. Type del1.BeginInvoke , where del1 is the variable that points to the delegate that you want to execute asynchronously.

  4. Type the parameters for the delegate function.

  5. Type ,cb , state after the last parameter of the delegate function. cb is the name of the variable you created in step 2. state is any variable or literal value. (The system will store the value and you can retrieve it later.)

  6. For information on what to do when the notification function executes in your class, read "Retrieving Results from Asynchronous Delegates," later in this chapter ( Figure 10.17 ).

    Figure 10.17 You can have .NET notify you when the asynchronous function is done executing by declaring a function such as FunctionDone, shown here. You then declare a delegate to contain that function and pass it as a parameter to BeginInvoke. When Task2 is done executing, the runtime will call FunctionDone.
     class Tasks {    public bool Task1(string desc)    {       return true;    }    public static bool Task2(string desc)    {       return true;    } } delegate bool TaskDel(string desc); public class WebForm1 : System.Web.UI.Page {  public void FunctionDone(   IAsyncResult ar)   {   }  private void Page_Load(object sender,                 System.EventArgs e)    {       TaskDel del1 =       new TaskDel(Tasks.Task2);  AsyncCallback cb = new   AsyncCallback(this.FunctionDone);  IAsyncResult rs =       del1.BeginInvoke(       "Calling Task1...",  cb,"Task2"  );    } } 

graphics/tick.gif Tips

  • As you type BeginInvoke you may notice that the intellisense feature doesn't list BeginInvoke as one of the methods . That's okay; keep typing. This is one instance where intellisense doesn't work correctly.

  • You can't execute combined delegates asynchronously.

  • Use the first approach (execute and wait) when you want to execute multiple functions asynchronously, each in different threads, and wait until all of them have completed.

  • Use the second approach (system alerts you when it's done) when you have only one function to execute asynchronously and you want to continue executing code in the main thread while the delegate function is executing.

  • When you use BeginInvoke , the first parameters are the parameters for the delegate, but only the input parameters are important. Control returns to your code after calling BeginInvoke before the asynchronous function is done executing, which means that any output values are meaningless. Once the function is done executing, you can read the return values. For details, see "Retrieving Results from Asynchronous Delegates," later in this chapter.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net