C # Asynchronous Operation

Actually, I have a hard time understanding the pair of BeginInvoke () and EndInvoke ().

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 end of the "asynchronous operation" BeginInvoke () ..?

2) What is the actual use of these pairs?

3) can I get simple and nice examples to better understand it?

+3
source share
4 answers

Imagine that you have a long task and you can only do one at a time. Usually, to do this, you have to stop doing the rest.

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

DoLaundry() {
    // boring parts here
}

, , , . - . , , , , , . , , , .

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

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

.

BeginInvoke. , (), , ( ), (state). IAsyncResult, , , . WaitHandle IAsyncResult .

:. , , IAsyncResult, . IAsyncResult EndInvoke.

EndInvoke: IAsyncResult . , , , .

, , . , , .., "/".

MSDN : http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.71).aspx

+11

BeginInvoke EndInvoke . #, - , begininvoke , Thread, - , , http://ondotnet.com/pub/a/dotnet/2003/02/24/asyncdelegates.html

+1

, , :
MSDN

:
............. BeginInvoke, CLR . . , , . BeginInvoke, , . EndInvoke / . callback BeginInvoke, EndInvoke , BeginInvoke.....

1) "EndInvoke()" " " BeginInvoke()..?
, ... .

2) ?
, ..

3) , ?
, Google : P

+1

Begin Invoke/End Invoke Window.

:

    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.");
    }

: Call BeginInvoke . , , , EndInvoke.

+1
source

Source: https://habr.com/ru/post/1723665/


All Articles