Asynchronous Operations in WCF

Request - response service operations in WCF cause the client to block while the service operation is executing. If a service takes five seconds to complete, the client application will freeze for the duration of the call waiting for the response.
 
You can use asynchronous programming pattern to enable a caller of any synchronous method to call it asynchronously. For example, while a web browser is downloading images in a web page, you can still scroll the page or navigate elsewhere.
 
Service Code
  1. namespace WCFService  
  2. {  
  3.     [ServiceContract]  
  4.     public interface IUserService  
  5.     {  
  6.         [OperationContract]  
  7.         string Authenticate(string UserName, string A_CryptKey);  
  8.         [OperationContract]  
  9.         List<User> GetApprovedUser();  
  10.     }  
  11. }  
  12.   
  13. namespace WCFService  
  14. {  
  15.     public class UserService : IUserService  
  16.     {  
  17.         public string Authenticate(string UserName, string A_CryptKey)  
  18.         {  
  19.             using (var Context = new UserServiceEntities())  
  20.             {  
  21.                 var user = Context.Users.Where(c => c.UserName == UserName && c.A_CryptKey == A_CryptKey).FirstOrDefault();  
  22.                 if (user != null)  
  23.                     return Convert.ToString(user.UserID) + "," + Convert.ToString(user.B_CryptKey);  
  24.                 else  
  25.                     return string.Empty;  
  26.             }  
  27.   
  28.         }  
  29.   
  30.         public List<User> GetApprovedUser()  
  31.         {  
  32.             using (var Context = new UserServiceEntities())  
  33.             {  
  34.                 List<User> User = Context.Users.Where(c => c.IsApproved == true).ToList();  
  35.                 return User;  
  36.             }  
  37.         }  
  38.     }  
  39. }  
Service configuration

  1. <system.serviceModel>  
  2.     <behaviors>  
  3.       <serviceBehaviors>  
  4.         <behavior>  
  5.           <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  6.           <serviceMetadata httpGetEnabled="true" />  
  7.           <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->  
  8.           <serviceDebug includeExceptionDetailInFaults="false" />  
  9.         </behavior>  
  10.       </serviceBehaviors>  
  11.     </behaviors>  
  12.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  13. </system.serviceModel>  
In client project solution explorer right click and select "Add Service reference". Now click on "Advanced" button in the Add Service reference dialog box and select "Generate Asynchronous Operations" check box. It will generate IAsyncResult class and two methods Begin<OperationName> and End<OperationName>.
 
First Begin<OperationName> is called by the client and then the client can continue executing code on its current thread while the asynchronous operation executes in a different thread. The client calls End<OperationName> for each call to Begin<OperationName> to get the result. A delegate is passed by the client to the Begin<OperationName>, which is called when the asynchronous operation is completed and can store state information from the Begin<OperationName> call.
 
WCF Client code

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using UserService;  
  8. public partial class Default : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.         UserServiceClient proxy = new UserServiceClient();  
  13.         IAsyncResult arUser;  
  14.         arUser = proxy.BeginAuthenticate("Mukesh""XY12@9", AuthenticateCallback, proxy);   
  15.   
  16.         //arApproveUser = proxy.BeginGetApprovedUser(GetApprovedUserCallback, proxy);  
  17.     }  
  18.   
  19.     // Asynchronous callbacks   
  20.     static void AuthenticateCallback(IAsyncResult ar)  
  21.     {  
  22.         string user = ((UserServiceClient)ar.AsyncState).EndAuthenticate(ar);  
  23.     }  
  24.     //static void GetApprovedUserCallback(IAsyncResult ar)  
  25.     //{  
  26.     //   List<UserService.User> user = ((UserServiceClient)ar.AsyncState).EndGetApprovedUser(ar);  
  27.     //}  
  28. }  
Client side configuration

  1. <system.serviceModel>  
  2.     <bindings>  
  3.       <basicHttpBinding>  
  4.         <binding name="BasicHttpBinding_IUserService" closeTimeout="00:01:00"  
  5.           openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"  
  6.           allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"  
  7.           maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"  
  8.           messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"  
  9.           useDefaultWebProxy="true">  
  10.           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"  
  11.             maxBytesPerRead="4096" maxNameTableCharCount="16384" />  
  12.           <security mode="None">  
  13.             <transport clientCredentialType="None" proxyCredentialType="None"  
  14.               realm="" />  
  15.             <message clientCredentialType="UserName" algorithmSuite="Default" />  
  16.           </security>  
  17.         </binding>  
  18.       </basicHttpBinding>  
  19.     </bindings>  
  20.     <client>  
  21.       <endpoint address="http://localhost:52949/UserService.svc" binding="basicHttpBinding"  
  22.         bindingConfiguration="BasicHttpBinding_IUserService" contract="UserService.IUserService"  
  23.         name="BasicHttpBinding_IUserService" />  
  24.     </client>  
  25. </system.serviceModel>

 


Similar Articles