In WCF 4.5, Microsoft introduced support for Task-based programming model based on TAP (Task-based Asynchronous Pattern) that is comparatively easy to implement, because most of the difficult work of developer is now moved to compiler. For a detailed reference to Asynchronous Programming in WCF 4.5, please follow here. In this WCF Tutorial, we are going to see task-based asynchronous operations in action. Two important keywords “async” and “await“are used for task-based asynchronous programming.Consider we have aWCF Service as follows:
{
[ServiceContract]
public interface IStudentService
{
[OperationContract]
List GetStudents();
}
public class Student
{
[DataMember]
public int StudnetId { get; set; }
public string StudentName { get; set; }
}
}
Our WCF Service implementation is as below:
{
List<Student> students = null;
{
students = new List<Student> {
new Student(){StudnetId=1, StudentName=”Imran”},
new Student(){StudnetId=2, StudentName=”Nauman”},
new Student(){StudnetId=3, StudentName=”Salman”}
}; return students;
}
}
Now, let’s compile and publish the WCF Service. So far things are same as we do normally for creating a WCF Service.
But if we have a client application and add a reference to this service using Visual Studio 2012 or higher with .NET 4.5, we will see the difference.
If we click on “Advanced…” button above, following screen will be displayed and we can find the option for “Generate task-based operations” as marked below.
If we generate proxy with above selected option, we will see asynchronous method “GetStudentsAsync” as shown below:
The calling method from client will be using “async” and “await” keywords as displayed in below code:
{
lblMessage.Text = “Fetching students data….”;
MyStudentService.StudentServiceClient client = new MyStudentService.StudentServiceClient();
var Result = await client.GetStudentsAsync();
gvStudents.DataSource = Result;
gvStudents.DataBind(); lblMessage.Text = “Students data fetched successfully.”;}
As compared to traditional asynchronous approach, task-based asynchronous operation is much easier in WCF 4.5 especially due to following factors:
- Proxy generated with Async automatically
- client code is straight forward using async and await keywords instead of callback methods.
Top 10 Interview Questions and Answers Series:
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions