Understand Task Based Async pattern in WCF 4.5

Understand Task Based Async pattern in WCF 4.5

In Visual Studio 2012 and WCF 4.5, there is a new option available to generate Task based operations so that the code from the client side can be then less complex. Task based asynchronous programming is now simplified and streamlined in .NET 4.5 through the use of keywords ‘await’ and ‘async’.

 

Step 1: Open Visual studio 2012 and create a blank solution, name it as ‘WCF_Task_Based_WCFService’. In this solution add a new WCF Service Application project targeting .NET 4.5 Framework. Name this project as ‘WCF_TaskBasedService’.

Step 2: Add the below code in IService.cs: 

using System.ServiceModel; 
namespace WCF_TaskBasedService 
{ 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        List<EmployeeInfo> GetEmployees();
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class EmployeeInfo
    {
        [DataMember]
        public int EmpNo { get; set; }
        [DataMember]
        public string EmpName { get; set; }
    }

 

Step 3: Implement the ServiceContract as below:

public class Service : IService 
{ 
EmployeeInfo[] Employees = null; 
public class Service1 : IService1
    {
    List<EmployeeInfo> lstEmployee = null;
        public Service1()
        {

            lstEmployee = new List<EmployeeInfo>{   
   new EmployeeInfo() {EmpNo=1,EmpName="A"}, 
   new EmployeeInfo() {EmpNo=2,EmpName="B"}, 
   new EmployeeInfo() {EmpNo=3,EmpName="C"}, 
   new EmployeeInfo() {EmpNo=4,EmpName="D"}, 
   new EmployeeInfo() {EmpNo=4,EmpName="E"}, 
   new EmployeeInfo() {EmpNo=5,EmpName="F"}, 
   new EmployeeInfo() {EmpNo=6,EmpName="G"}, 
   new EmployeeInfo() {EmpNo=7,EmpName="H"}, 
   new EmployeeInfo() {EmpNo=8,EmpName="I"}, 
   new EmployeeInfo() {EmpNo=9,EmpName="J"}
};
        }

        public List<EmployeeInfo> GetEmployees()
        {
            return lstEmployee;
        }
    }


Step 4: Build the service and publish it on IIS (optional).

 

Step 5: In the same solution, add a new WPF Project targeted to .NET 4.5 and name it as ‘WPF_Client’. Design the MainWindow.xaml as below:

<Grid>
        <Grid>
            <DataGrid  x:Name="dgEmp"  HorizontalAlignment="Left" Margin="74,26,0,0"  VerticalAlignment="Top" 
  Height="338" Width="650"/>
            <Button  x:Name="btnGetEmployees"  Content="Get Employees" HorizontalAlignment="Left" 
  Margin="74,389,0,0"  VerticalAlignment="Top" Width="650" Height="76" 
  Click="btnGetEmployees_Click"/>
            <TextBlock  x:Name="txtInfo"  HorizontalAlignment="Left"  Margin="74,470,0,0"  TextWrapping="Wrap" 
  Text="TextBlock"  VerticalAlignment="Top"  Height="38" Width="650"/>
            </Grid>

        </Grid>

Step 6: Add the WCF Service Reference in the Project


In the ‘Add Service’ Window, enter address of the WCF Service. 

Click on Go and click on the Radio Button ‘Generate Task based’ operations as below


This adds the proxy in the WPF application. If you open the proxy class, the method ‘GetEmployeeAsync’ is generated as follows


Step 7: Now the above method can be called in WPF application on the Click event of the button

private async void btnGetEmployees_Click(object sender, RoutedEventArgs e)
        {
            txtInfo.Text = "Data is Not Received Yet....";
            EmployeeService.Service1Client Proxy = new EmployeeService.Service1Client();
            var Result = await Proxy.GetEmployeesAsync();
            dgEmp.ItemsSource = Result;
            txtInfo.Text = "Data Received...."; 
        }

If you carefully see the above code, you will find that the Click event method is decorated with ‘async’ keyword. This indicates that the method contains an Async call. The method ‘GetEmployeeAsync‘ is called with the ‘await’ keyword, this means the asynchronous call will be completed and then the data will be displayed in the DataGrid.

Step 8: Run the application and click on the Button. The result will be as shown below


The Text shows that the call is in progress. Await for 10 seconds and the result will be as follows 


Conclusion

Using Task Based Async pattern, we can program in a more linear fashion that is easy to read compared to Event Based Async Patter (EAP), where you have one method initiating the call and another method handling the callback after the task is completed.

Thus by exposing Task based operations to the client, the client side code can be made less complex.

 

Click here to Download the source code.


Happy Coding.


comments powered by Disqus

Related Articles