Wednesday, June 30, 2010

Async Calls in C# – Should I blog about this?

Well, this may be for me to keep track but thought it would be usefull as I see more more and junior developer who do not understand the importance of Async programming and make blocking calls and it is frustrating especially in Web or Online apps.

There are too many frameworks available that you can take advantage of today. Another great video here I just wanted to give a very very simple steps to get this whole asynchronous business going. I assume that you know all the delegate concepts. Even if you dont know, dont worry, you really dont need to.

------------------------------------------------------------------------------------------------------

Scenario 1- Simplest of all. You want to call a function without blocking the main thread and dont care about return value dont want to know when called function finishes execution

a. Create a delegate –

 public delegate string  GetName (string myname);     –> note that you generally know what function to call and so you can decide on the delegate signature.

b. Then create object of delegate

GetName nameGetter = new GetName(GetMyRealName); <— GetMyRealName  is the actual function we want to call in Async manner.

c. Then Simply do

IAsyncResult result = nameGetter.BeginInvoke(name,null,null); <- Param 1 is parameter to original function, first null is Callback (explained latter) and last is object state (explained later)

A method GetMyRealName will be called without blocking your main thread. This is as simple as that.

*note that if your called function throws exception it will not come up

------------------------------------------------------------------------------------------------------

Scenario 2-  You want to call a function without blocking the main thread, At the same time do something else and then see what is the result of your async function

------------------------------------------------------------------------------------------------------

Scenario 3-  You want to call a function without blocking the main thread, then have another function called when your called function finishes execution

No comments: