Friday, 26 August 2016

What is Async & Await in C# .net?

What is Async & Await in C# .net?

If you are familiar with normal ASP.net C# code then this would be easy for you to understand.
just see the below code I'll explain it later (don't go with long red arrow)





In above its a simple asp.net web page code behind where someone click the Button1_Click,and then a callprocess() function get called.after this function we add "Program finish" text in a ListBox1.and increment value of a variable val to 10.

Now how do you think the code need to behave.


STEP 1>STEP 2>STEP3

WHAT you assume normally 

1.int val=0 set in top and declared in last of the button click so val>=10 must fail. right?

2.Listbox add item "Program finish" in last but before it, callprocess() method comes which adding a item "Long Process finish" .so ListBox1 must have LongProcessFinsh in top and Programfinish after that .right?


BUT what realy happens?

Let me tell you everything happen exactly opposite of it.

STEP3(as callprocess() is async other code could not wait for it which has await attach to it)>STEP1>STEP2


In callprocess function the condition "if(val>-0" have value 10 in it already.and ProgramFinish is already added in Listbox1 before LongProcessFinish.

Its because we declare await inside a function (await always do a task(your async kind of task))await LongProcess();


and when you added it you must declare that function with async.

        public async void CallProcess()
        CallProcess();//this is detected as async with calling himself await
        this.ListBox1.Items.Add("Program finish");//they executed without wait
        val += 10;                                                           //they execute without wait


so what basicaly async/await/Task doing 


Async:keyword to declare yes this is a async method

Await:this code will execute but telling other code part dont wait for me I am coming from behind.

Task:like void,we perform here our task which return type is 

Void: Means nothing to return

Task: It will perform one operation, a little similar to void but the difference is there.

Task<T>: Will return a task with a T type parameter. (I hope you are familiar with the concept of T)










No comments:

Post a Comment

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...