Thursday 4 April 2013

ASync Methods in C#


Hi there, as we all have the habit of prioritizing our daily tasks, and some things (which are boring and repetitive ones), we postponed them for the later time, like that we can prioritize the tasks in .net programming  too,  with the help of these “ASync Methods”, as we all know about the primary difference between synchronous and asynchronous calls, Once again, will refresh that, we can have synchronous calls when we expecting for an output from the called method, but in case of asynchronous calls we may wait for the output or we can perform the other actions not by waiting.

“The primary scenario is the threads which usually takes more time to execute and also their output is not a main concern, will be designed as ASync Methods.”
2 Use Cases here which I came across recently about, the real usage of these ASync Methods,
Use Case: 1
You are uploading the document from UI (website) that document which gets replicated in different repositories [say 3 libraries], each library will take around 3 secs, to create that new document  in theirs. From the first creation of the document in the first library itself, the UI should be responsive, as an alert with ‘Creation Done/Failed!!’ So the remaining document libraries can be updated, later so here, we can use the above said postponement thing.
Use Case: 2
As you all had an experience of auditing the method calls, [i.e., just a record for the later purpose, how much times an method is used by whom n all]. Here the main or actual functionality of the method is needed for the UI or other applications, the audit purpose calls, whether it’s an insert to db or writing to flat file, is not the actual functionality of the method. Hence we can give this auditing work to the ASync Methods.
Syntax / Usage:
In C#, Asynchronous calls are made by using delegate. A delegate is an object that wraps a function. That delegate object has got BeginInvoke() and EndInvoke() methods which calls the wrapped up function asynchronously.
1. Say, you have methods named UserFeed & PublicFeed,
public string UserFeed(string userid,string filters){
                string userfeedResult = getuserfeed();//getting feed logic from DB  — main functionality
                AuditLog(userid,”USERFEED”, userfeedResult); // for audit purpose call
                return userfeedResult;  }
2. public string PublicFeed(string userid,string filters){
                string pubfeedResult = getPublicFeed(); //getting feed logic from DB  — main functionality
                AuditLog(userid,”USERFEED”, pubfeedResult);  // for audit purpose call
                Return pubfeedResult;
}
3. Private void AuditLog(string usrid,string method,string result) { // db insert }
The above said 2 methods, have a call for AuditLog(), which we can have it as ASync Call, like below,
4. delegate void AsyncAuditLog(string userid, string consumedMethod, string feedresult);   //declare a delegate with same param list as that of our AuditLog() method.
5. Replace the call for AuditLog() method as follows,

public string UserFeed(string userid,string filters){
                string userfeedResult = getuserfeed();//getting feed logic from DB  — main functionality
               AsyncAuditLog asyncAudiLogInvoke = new AsyncAuditLog(AuditLog);
               IAsyncResult result = asyncAudiLogInvoke.BeginInvoke(userID, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), consumedStatus, null, null);
                return userfeedResult;
}
 Inspite of Audit DB insert, our methods will return the result as quick as it’s fetched. The AuditLog() will happens in another thread.
PS : By this way you can save 100 millisecs. [verified], but it depends on you to get the call back value, and verify them.
Cons of ASync Methods:
As ASync methods are cunning, and become tortuously tricky to follow when applied in a real application, which naturally makes, any decompilation a bit of challenge. Debugging too, a little bit tedious here, as we not know about the nature of the compiler’s implementation for the ASync Method handling hence threads with alternate ids may get logged into your logs.
Happy Coding  :)

No comments:

Post a Comment