Tuesday, August 9, 2011

BeginInvoke() and EndInvoke()

BeginInvoke() call methods without really knowing when it is finished. But with EndInvoke(),
it is possible to do a few more things. First of all,
EndInvoke will block until your function
 completes execution; so, calling
BeginInvoke followed by EndInvoke is really almost like
calling the function in a blocking mode (because the
EndInvoke will wait until the function
completes). But, how does the .NET runtime know how to bind a
BeginInvoke with an
EndInvoke? Well, that’s where IAsyncResult comes in. When calling BegineInvoke,
the return object is an object of type
IAsyncResult; it is the glue that allows the framework
 to track your function execution. Think of it like a little tag to let you know what is going on
 with your function. With this little powerful super tag, you can find out when your function
 completes execution, and you can also use this tag to attach any state object you might want
 to pass to your function. Okay! Let’s see some examples so this doesn't become too confusing
... Let's create a new function.

private void WaitForOneSecond()


    // sleep for one second!



private void UsingEndInvoke()
    // create a delegate of MethodInvoker poiting to our Foo function.
    MethodInvoker methodInvokeDelegate = new MethodInvoker(WaitForOneSecond);
    // start FooOneSecond, but pass it some data this time!
    // look at the second parameter
    IAsyncResult tag =
        methodInvokeDelegate.BeginInvoke(null, "passing some state");
    // program will block until FooOneSecond is complete!
    // once EndInvoke is complete, get the state object
    string strState = (string)tag.AsyncState;
    // write the state object
    Trace.WriteLine("State When Calling EndInvoke: "
        + tag.AsyncState.ToString());


No comments :

Post a Comment