?

Log in

Previous Entry | Next Entry

How to invoke WCF service asynchronously?

As a service developer we just simply create the service, host it and expose the endpoints. Now whether those functions should be called synchronous or asynchronously is client’s lookout.

When the proxy class of our service get generated in the client side, async version of all our service methods also get generated automatically.
For example : If our service contain methods such as GetString, GetCustomer then our proxy class will contain four methods, GetString,GetCustomer,GetStringAsync,GetCustomerAsync.

There are two approaches normally a .net developer can follow,

  1. Event based approach

  2. Task based approach

1. Event based approach

Both the asynchronous methods will never return anything. Return type will be void. Instead on completion, some events will be raised.

Complete code:

privatevoid button1_Click(object sender, EventArgs e)
{
   FirstClient c = newFirstClient("WSHttpBinding_IFirst");
   c.GetStringCompleted += c_GetStringCompleted;
   c.GetStringAsync();
   .
   .
}
.
.
.
.
voidc_GetStringCompleted(object sender, GetStringCompletedEventArgs e)
{
label2.Text = e.Result;
}

2. Task based approach

In this approach C# 5.0 asycn await pattern will be used. Here asynchronous methods will return “Task” object instead of direct return value which can be awaited later

privateasyncvoid button1_Click(object sender, EventArgs e)
{
       FirstClient c = newFirstClient("WSHttpBinding_IFirst");
       Task<string> r=c.GetStringAsync();
   .
   .
   .
label2.Text += "\n" + await r;
}

For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See following video on WCF concurrency and throttling: -



Click and see here for more step by step learning WCF(Windows Communication Foundation).
Copy right www.questpond.com

Buy 600+ Real Time Interview Videos

Call +91-22-66752917 or mail us on questpond@questpond.com for more details on C#, .NET, ASP.NET, SQL Server interview question videos.

SQL Server interview question videos

Latest Month

January 2017
S M T W T F S
1234567
891011121314
15161718192021
22232425262728
293031    

Tags

Powered by LiveJournal.com