C # callbacks, call order and return

A simple question about callbacks. Do callback functions return to the next line in the calling function after completion?

class A
{
 public delegate void A();
 public event A onA;

 public void func()
 {
   //some code 1
  onA();
  //some code 2 
 }

So, the question is, will the onA event go and execute the corresponding handler, and then return to the "some code 2" bit or is it asynchronous and the code will not wait until the event is fully processed?

I hope the question is clear.

Thank }

+5
source share
5 answers

Yes, in your example, onA () will fire all event handlers connected to A to fire. These are just the methods to be called. After all of them will be called, control will return to func () function.

- . .

.

+2

: . , BeginInvoke.

+3

assync. .

+2

, assync. func() onA().

BeginInvoke Threading, , assync.

.

+1

, . , -.

, 'onA' , onA() .

"Foo" "OnFoo", . , , - : -

class Foo // Class and member names must be distinct
{
    public delegate void ADelegate();
    public event ADelegate A;

    private void OnA()
    {
        if(A != null)
            A();
    }

    public void Func()
    {
        // Some code...
        OnA();
        // More code...
    }
}

, BeginInvoke() EndInvoke(), : -

class Foo // Class and member names must be distinct
{
    public delegate void ADelegate();
    public event ADelegate A;

    private void OnA()
    {
        if (A == null) return;

        // There may be multiple subscribers, invoke each separately.
        foreach(ADelegate del in A.GetInvocationList())
            del.BeginInvoke(SubscriberCallback, del);
    }

    private void SubscriberCallback(IAsyncResult result)
    {
        var del = (ADelegate) result.AsyncState;
        del.EndInvoke(result);
        // Do something in the callback...
    }

    public void Func()
    {
        // Some code...
        OnA();
        // More code...
    }
}

, (-) , , .

Please note that the "callback" is the method that you specify in the asynchronous BeginInvoke (since it "appealed" after the async-work) and does not return to Func (), because it is executed in a separate thread.

0
source

All Articles