views:

214

answers:

4

Acctually I have hardtime in understanding BeginInvoke() and EndInvoke() pair.

class AsynchronousDemo
{

    public delegate void DemoDelegate();
    static void Main()
    {

        DemoDelegate d = PrintA;

        IAsyncResult AResult = d.BeginInvoke(Callback,null);
        d.EndInvoke(AResult);
        Console.ReadKey(true);
    }

    static void PrintA()
    {
        Console.WriteLine("....Method in Print A Running ....");
        Thread.Sleep(4000);
        Console.WriteLine("....Method in Print A Completed...");
    }


    static void Callback(IAsyncResult ar)
    {
        Console.WriteLine("I will be finished after method A 
        completes its execution");
    }
}

1) Do we use "EndInvoke()" to indicate the ending "asynchronous operation" of BeginInvoke()..?

2) What is the real use of those pair?

3) can i get some simple and nice examples to understand it more properly?

+1  A: 

BeginInvoke is starting an Asynchronous operation EndInvoke is waiting to the end of that function and returning result. it's an another way to execute threading in C#, the great features are that begininvoke take the thread fromm thread pool, which is not correct for Thread class, and another one is that you can pass parameters and get result to thread function in more easy way. here is an example http://ondotnet.com/pub/a/dotnet/2003/02/24/asyncdelegates.html

ArsenMkrt
+1  A: 

I don't know how to explain it well enough but this article should help:
Asynchronous Programming Using Delegates on MSDN

Excerpt:
.............If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.....

1) Do we use "EndInvoke()" to indicate the ending "asynchronous operation" of BeginInvoke()..?
No, you use that to obtain the return values or... see above

2) What is the real use of those pair?
So you can make asynchronous call on a synchronous method etc

3) can i get some simple and nice examples to understand it more properly?
I'm pretty sure google can do this better than me :P

o.k.w
+1  A: 

I use the Begin Invoke / End Invoke construct to run Window's services.

For example:

    public ServiceName()
    {
        //constructor code goes here
    }

    protected override void OnStart(string[] args)
    {
        ExecuteDelegate ed = new ExecuteDelegate(Execute);
        AsyncCallback ac = new AsyncCallback(EndExecution);
        IAsyncResult ar = ed.BeginInvoke(ac, ed);
        Log.WriteEntry("Service has started.");
    }

    protected void EndExecution(IAsyncResult ar)
    {
        ExecuteDelegate ed = (ExecuteDelegate)ar.AsyncState;
        ed.EndInvoke(ar);
        Stop();
        Log.WriteEntry("Service has stopped.");
    }

    protected void Execute()
    {
       //Code goes here
       ...
    }

    protected override void OnStop()
    {
        Log.WriteEntry("Service has stopped.");
    }

Essentially: Call BeginInvoke to start execution of a method in a new thread. When the thread is over then the method that is called when the thread is joined should call EndInvoke.

Matt Ellen
+4  A: 

Imagine you have a long task to do, and can only do one thing at a time. Normally, in order to do it, you'd have to stop doing everything else.

// pseudocode
Main() {
    DoLaundry()
    GoAboutYourDay()
}

DoLaundry() {
    // boring parts here
}

Now imagine you want to be able to go about your day while your laundry is being made. One solution would be to get someone else to do it. So you take it to a cleaning shop, tell them what to do, give them your clothes, and tell them to phone you when they're done. In return, they give you back a ticket so they can find your clothes again when you want them back.

// pseudocode
Main() {
   ticket = DoLaundry.BeginDoing(CallMeWhenDone)
   GoAboutYourDay()
   ticket.WaitUntilDone()
}

CallMeWhenDone(ticket) {
   cleanLaundry = DoLaundry.FinishDoing(ticket)
}

This is how asynchronous operation works.

BeginInvoke You tell the program what you need to be done (the delegate), what to call when it's done (callback), and what to do it with (state). You get back an IAsyncResult, which is the object that you need to give it back in order to receive your result. You can then do other stuff, or use the WaitHandle in the IAsyncResult to block until the operation's done.

Callback: When the asynchronous operation finishes, it will call this method, giving you the same IAsyncResult as before. At this point, you can retrieve your state object from it, or pass the IAsyncResult to EndInvoke.

EndInvoke: This function takes the IAsyncResult and finds the result of the operation. If it hasn't finished yet, it'll block until it does, which is why you usually call it inside the callback.

This is a pattern that's often used all over the framework, not just on function delegates. Things like database connections, sockets, etc. all often have Begin/End pairs.

MSDN has documentation on the pattern here: http://msdn.microsoft.com/en-us/library/2e08f6yc%28VS.71%29.aspx

Ilia Jerebtsov
Excellent explanation.would be very useful for beginners like me.