Task based WCF Services in .NET 4.5

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 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 the Task Based Async pattern, we can in a more linear fashion that is easy to read compared to 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 (Github)




About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years 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). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

No comments: