Hello Guys, So in the last article we talked about What is
delegate and how can we create a delegate.
In this article we will discuss what are the ways available
to call a delegate and what are the differences in between ?
There are different ways in which you can invoke
delegates to get a synchronous or an asynchronous behavior.synchronous - Using Invoke we can achieve this and in this delegate execute synchronously on the same thread. So in general when you want to invoke a delegate and want to wait for its completion before current thread continues then Invoke is the right choice. Details you can see in this article -
Asynchronous
Way - We can achieve this using BeginInvoke, It means you
do not want that main thread wait for
the completion of the delegate. In this scenario the delegate and current
thread can work in parallel.
Point to notice here is You can achieve Asynchronous way using Delegate.BeginInvoke or
creating a new thread then Which one to prefer and Why ?
Delegate provides a very less control over async behavior as
when you invoke a delegate you can fetch the result using EndInvoke but you cannot
terminate the process. While creating a thread you have more control on Async
behavior. So in my understanding creating a Thread is better than invoking a
delegate in Async way.
Implementation
of BeginInvoke -In the above example we saw how can we invoke a delegate using BeginInvoke.
So now in case GenerateMainXml has to return some value. How
can we handle this situation ?
Answer
is EndInvoke.
Calling EndInvoke will always block your main thread until
it completes the execution. There are two ways of calling EndInvoke. One is as
a callback and another one is direct way.
Direct way of calling an EndInvoke() -So in the above example we created a Square number function and assigned it to a delegate. Called using BeginInvoke and on the same delegate called the EndInvoke method to get the results.
There is one problem in this approach. Use case of
BeginInvoke is to get asynchronous way of implementing one of the method. But
after calling EndInvoke we are telling to main thread to wait until delegates execution
completes. Then only we can fetch the results .
So now
what is the solution ?
Calling EndInvoke as Callback method. In this
way we tell delegate once it completes the execution, call the callback method and tell us the results.
So main thread won't be blocked.Looks Good :)
DynamicInvoke : It is similar to Invoke, it invokes a delegate in asynchronous way. The only benefit is it takes object[] as parameter. So it does boxing and unboxing at run time.
Correct implementation is -
So we can see in the above example we can pass an object array as aparameter in dynamicinvoke and the result will also be a object type. So this is usefule when you are not aware of the type but it will be damn slow. So think before using it.
Hope you like reading the article. Please inbox me in case
of any confusion is in your mind.
Happy Coding:)