WCF Task Based Async Pattern in .NET 4.5

Posted by: Mahesh Sabnis , on 2/19/2014, in Category Windows Communication Foundation (WCF)
Views: 87126
Abstract: In WCF 4.5, there is a new option available to generate Task based async operations so that the code from the client side can be then less complex. In this article, we will see how to implement it.

Task based asynchronous programming is now simplified and streamlined in .NET 4.5 through the use of keywords ‘await’ and ‘async’. These keywords help makes asynchronous code look similar to synchronous coding, making it easier to write and understand Asynchronous code. Those who have used WCF service might have used the Asynchronous contract generation while adding WCF service reference in the Client application. The Asynchronous contracts are required so that client can make an Asynchronous call to WCF service performing time consuming operations.

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. In the following example we will see how to implement it.

 

 

Sample WCF Application

Step 1: Open VS2012 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’. Rename IService1.cs to IService.cs and Service1.svc to Service.svc.

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

using System.ServiceModel;
namespace WCF_TaskBasedService
{
[ServiceContract]
public interface IService
{
  [OperationContract]
  EmployeeInfo[] GetEmployees();
}
[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 Service()
{
  Employees = new 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 EmployeeInfo[] GetEmployees()
{
  return Employees;
}
}

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>
< 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>

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:

service-reference-settings

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

public System.Threading.Tasks.Task<WPF_Client.MyRef.EmployeeInfo[]>
GetEmployeesAsync()
{
return base.Channel.GetEmployeesAsync();
}

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....";
MyRef.ServiceClient Proxy = new MyRef.ServiceClient();
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:

wcf-app

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

main-window

The above screenshot shows the final result.

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.

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Kurt Ari on Tuesday, February 25, 2014 5:08 AM
This is cool. I am surprised none of the services layer devs in my team had an idea how this works. I am glad now they do!
Comment posted by Mahesh Sabnis on Friday, April 4, 2014 4:48 AM
Hi Kurt Ari,

  Thanks a lot.

Regards
Mahesh Sabnis
Comment posted by anonymous on Saturday, May 17, 2014 7:12 AM
in reference service settings my reference setting part is disable. i am not able to enable or disable anything
Comment posted by Dominique on Monday, May 26, 2014 5:40 AM
Take-based operations are completedly disabled.

Silverlight 5 and asp.net web project.
Comment posted by Surya Prakasa Rao N on Thursday, December 25, 2014 1:01 AM
Make sure the Client application's target framekwork 4.5, then only the task-based operations... will be enabled.