How delegate can be used for callback in c#?what is Asynchronous Delegate?

Kindly read blog on delegate before starting this blog

Consider below example where delegate is pointing to function which is time consuming.

Note: when below console app started a thread is created which will execute the statements  in Main method sequentially.Fist statement creating instance of delegate.Second statement is invoking delegate.Function pointed by delegate(“ReturnLength(string name)”) will start executing.The first line in function is Thread.Sleep(2000).

AD

Thread.Sleep(2000) will cause thread to sleep for 2 second.After 2 second next Console.WriteLine(“work ReturnLenth….”) will be printed and then function is return and remaining line is executed.

In short you need to wait for function “ReturnLength” to get executed then only code below “mydelegate.Invoke” will be executed as execution of code is sequential and only one thread is executing code. Can we execute function “ReturnLength” in parallel ?

Result is yes by calling delegate using BeginInvoke method(by calling delegate asynchronously).

AD2.png

As you can see in above image first input parameter to method BeginInvoke  is parameter which will be passed to function “ReturnLength”. Second input parameter is callback method which will be called when function “ReturnLength” is completed. In third input parameter we are passing delegate “mydelegate”so that we can access it in callback method.

How to access “mydelegate” in callback method is explained above image.

Callback method will take only one input parameter of type IAsyncResult.

So in above example once mydelegate.BeginInvoke is called function “ReturnLength” will be executed parallel on another background thread and next line after “mydelegate.BeginInvoke” will print immediately. Now control will not wait for “ReturnLength”  to get completed as this function is executed by seprate background thread. Once “ReturnLength” is completed the callback method will be called. callback method  will be also executed on background thread. Input to EndInvoke will be parameter of type IAsyncResult. On calling EndInvoke we get result return by “ReturnLength”. If let’s say method “ReturnLength” is not returning any value then also you should call EndInvoke.

If there is error in “ReturnLength” then it will not caught until you call EndInvoke .You should call EndInvoke using try catch.

Let’s say we have simple window form(see below image). When we click on button time consuming function is called and textbox adjacent to label name is set with some string.

AD3

One thing you will notice when you click on button your UI will freeze until, time consuming function (“Fetchname(int id)”) is completed. This is because winform also work on single threaded model. It means all statement inside event handler will be executed by single thread sequentially. When we call func(), main thread wait for func to get completed. Hence UI will freeze. Once Fetch name is completed then message box is shown (In short once function pointed by fun is completed then only line below it get executed), and now you can click on UI(it will no more freeze).

If you again click on button1 then same thing happen as above (your UI will freeze until time consuming function (“Fetchname(int id)”) is completed ).We can solve above problem by using asynchronous delegate. Using asynchronous delegate we can execute function (“Fetchname(int id)”) on background thread.

AD4

As you can see above, after call “func.BeginInvoke ()” in event handler the control move to next line, as there is no line after “func.BeginInvoke ()” hence control will return. Now UI will not freeze as it is not waiting for “func.BeginInvoke ()” to get completed. Once function (“Fetchname(int id)”) is  completed callback method will be called. Above call back method is “CallbacktoUpdateUI”. As callback is executed on background thread hence we cannot directly update UI control. UI control will be updated only by main thread which created it. Hence we have to use special syntax “textbox2.Invoke ()” and it takes delegate. We have passed action which is updating textbox. This action will be queued to main thread. So main thread will update textbox. In wpf we use dispatcher for updating UI other than main thread.

Published by

dotnetwithwindowandweb

I am dot net developer interested in web and windows technology.My major skill set are c#,multhithreading,linq,winform,wpf,WCF,Sql server and Angular

3 thoughts on “How delegate can be used for callback in c#?what is Asynchronous Delegate?”

  1. “As you can see in above image first input parameter to method EndInvoke is parameter which will be passed to function ”

    I think in above line it should be BeginInvoke in place of EndInvoke

    Like

Leave a comment