Thursday, April 25, 2013

WCF- Asynchronous Service Operations


Example :



Interface :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WC_MetaDataMethod
{
    [ServiceContract]
    public interface IService1
    {
    // Here we defined two parameters Message and waitperiod(after how much time message will display)
        [OperationContract]
        string SimpleMethod(string msg,int waitperiod);
    }
}


Service :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WC_MetaDataMethod
{
    //Method implimentation.
    public class Service1 : IService1
    {
        public string SimpleMethod(string msg,int waitperiod)
        {
            // Thread will sleep for time period passed be client in waitperiod variable
            System.Threading.Thread.Sleep(waitperiod);
            return "Hello " + msg;
        }      
    }
}


WebConfig :
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="false" />
    <behaviors>
     
     
      <serviceBehaviors>
        <behavior name="SimpleServiceBehavior">        
          <serviceMetadata httpGetEnabled="true"  policyVersion="Policy15"/>     
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
     
     
    </behaviors>


    <services>
      <service name="WC_MetaDataMethod.Service1" behaviorConfiguration="SimpleServiceBehavior">
        <endpoint name="" address="http://localhost:56653/Service1.svc" binding="wsHttpBinding" contract="WC_MetaDataMethod.IService1"/>

        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

In order to setup Async calls do the following:
  • Right click on the service reference
  • Select ‘configure service reference’
  • Check ‘Allow generation of asynchronous operations’
  • Ensure ‘Generate asynchronous operations’ is selected  and Click OK
  •  


Now when creating a new proxy object you will have access to extra methods as following



Client:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {

Console.WriteLine("Operations  Started");           
client2.ServiceReference1.Service1Client Proxy = new client2.ServiceReference1.Service1Client();
           
Proxy.BeginSimpleMethod("Dear, display after waiting for 5 Seconds",5000, AscmMYCallBackFunction_With_Wait, Proxy);
          

client2.ServiceReference1.Service1Client Proxy2 = new client2.ServiceReference1.Service1Client();         
Proxy2.BeginSimpleMethod("Dear, No Wait", 0, AscmMYCallBackFunction_With_Wait, Proxy2);
     
Console.ReadLine();
        }

        protected static void AscmMYCallBackFunction_With_Wait(IAsyncResult iresult)
        {            
            var prox = (client2.ServiceReference1.Service1Client)iresult.AsyncState;
            var result = prox.EndSimpleMethod(iresult);
            Console.WriteLine(result);
            Console.ReadLine();             
        }

    }
}


The BeginSimpleMethod method takes the parameter (string), the asynchronous callback (AscmMYCallBackFunction_With_Wait) and the state object(Proxy).
The asynchronous callback method  AscmMYCallBackFunction_With_Wait, just gets the proxy out of the IAsyncResult.AsyncState again and we invoke the EndSimpleMethod on the proxy with as parameter the IAsyncResult. The EndSimpleMethod returns the result of our operation.

Second Method :
In this Before we call  the  SimpleMethodAsync, we defined which operation will handle the callback of the asynchronous operation, by SimpleMethodCompleted.

At the callback method we can just get the result from this e.Result.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Operations  Started");

            client2.ServiceReference1.Service1Client Proxy = new client2.ServiceReference1.Service1Client();
            Proxy.SimpleMethodCompleted += AscmMYCallBackFunction_With_Wait;
            Proxy.SimpleMethodAsync("Dear, display after waiting for 5 Seconds", 5000);


            client2.ServiceReference1.Service1Client Proxy2 = new client2.ServiceReference1.Service1Client();
            Proxy2.SimpleMethodCompleted += AscmMYCallBackFunction_With_Wait;
            Proxy2.SimpleMethodAsync("Dear, No Wait", 0);
            Console.ReadLine();

        }

protected static void AscmMYCallBackFunction_With_Wait(Object sender, client2.ServiceReference1.SimpleMethodCompletedEventArgs e)
        {          
            var result = e.Result;
            Console.WriteLine(result);
            Console.ReadLine();
        }

      }
    }


Third method (with lambda expressions):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Operations  Started");
          
            client2.ServiceReference1.Service1Client Proxy = new client2.ServiceReference1.Service1Client();
            Proxy.SimpleMethodCompleted += (sender, e) =>
                {
                    var result = e.Result;
                    Console.WriteLine(result);
                    Console.ReadLine();

                };
            Proxy.SimpleMethodAsync("Dear, display after waiting for 5 Seconds", 5000);

            client2.ServiceReference1.Service1Client Proxy2 = new client2.ServiceReference1.Service1Client();
            Proxy2.SimpleMethodCompleted += (sender, e) =>
            {
                var result = e.Result;
                Console.WriteLine(result);
                Console.ReadLine();

            };           
            Proxy2.SimpleMethodAsync("Dear, No Wait", 0);
            Console.ReadLine();
            //**************
       }
    }





2 comments :

  1. 3rd(lamda expression) so nice lavi..what is next article.

    also and i am excepting next article with new features of wcf 4.5 and sliverlight and asp.mvc.

    i am week in applicationpools, app domain ,workerprocess..ect

    ReplyDelete
  2. difference between asyn operations and duplex contract.

    ReplyDelete