callbacks in c#, calling order and return
A simple que开发者_运维技巧stion on 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 onA event go and execute the respective handler and then come back to 'some code 2' bit or is this asynchronous and code will not wait for the event to be fully handled?
I hope the question is clear.
Thanks }
The way you used delegate: is synchronous. If you want asynchronous you must invoke delegate with: BeginInvoke method.
Yes, in your example onA() will trigger all over the event handlers hooked up to A to fire. They are just methods that will be called. After they are all called, control will return to func().
It is not asynchronous - you are only using one thread. Everything will happen in a well defined order.
A good way to experiment would be to step through the code in your example using the built in debugger.
Your code isn't assync. But you can Use Delegates Asynchronously.
No, calling a event isn't a assync thing. Your code func()
will only continue after onA()
ends running.
You would use BeginInvoke
or Threading
if will wants assync code running.
Read more about delegate invokes here.
As others have pointed out, this is entirely synchronous. If you wanted to execute this asynchronously you would have to write this differently.
Additionally, if the event 'onA' is not subscribed to, onA() will raise a null reference exception.
The usual pattern is to define an event 'Foo' and a method 'OnFoo' which you call when the event occurs. From the name of the event I suspect this is what you desire - e.g.:-
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...
}
}
If you want to call the subscribed event handlers asynchronously you can use BeginInvoke() and EndInvoke() thus:-
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...
}
}
Note that this code won't wait to finish executing the event subscriber(s), you would have to thread the async result through the event call to ensure this happens.
Note that the 'callback' is the method you specify in the asynchronous BeginInvoke (since it is 'called back' once the async work is done), and doesn't return to Func() as it is executed in a separate thread.
精彩评论