Hi, last few days I got some questions from few folks that they are confused on how to call a WCF service in WinRT (Windows 8). This confusion occurs mainly if you are Silverlight dev or Windows Phone 7.5 dev and you are used to the traditional async method and the CompletedEvent.
In Silverlight these two are very handy and generated by the VS.
Think a very simple WCF service that you get once you create a WCF Application project in the Visual Studio. It comes with a simple method GetData which accepts an int and returns a string.
In Silverlight, VS generates the async method and the async CompletedEvent method for us. so we can simply call the service and get the results like this.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Service1Client proxy = new Service1Client();
proxy.GetDataCompleted += (GetDataSender, Ev) =>
{
TxtName.Text = Ev.Result;
};
proxy.GetDataAsync(10);
}
But in WinRT if you try do the same thing you soon will find that you are missing the CompletedEvent.
This is handled differently using the await and async keywords in C# 5.0 Read it in detail here.
Here’s the implementation detail of how you can call a WCF service in WinRT. Click to enlarge the image.

As you see the GetDataAsync method generated by the VS returns an awaitable Task. So it is simple than Silverlight, this what you have to do. Simple at its best.
But it is better to know how things work, but that is beyond the scope of this article and you can learn about it here
But what if you need to have a separate Application logic layer and wants to do some processing in the data returned by the service. (more often you need that)
Here’s a way to get the CompletedEvent architecture from Application logic and notifying it to the UI. I’m having my own even handler here.
Create a Class1 (your application logic layer)
class Class1
{
public event EventHandler<MyWebServiceEventArgs> DataProcessed;
public void HandleMethod(int value)
{
ProcessData(value);
}
private async void ProcessData(int value)
{
Service1Client proxy = new Service1Client();
string result = await proxy.GetDataAsync(value);
DataProcessed(null,new MyWebServiceEventArgs(result));
}
}
Create MyWebServiceEventArgs derived from EventArgs
public class MyWebServiceEventArgs : EventArgs
{
private string _myVar;
public string MyProperty
{
get { return _myVar; }
set { _myVar = value; }
}
public MyWebServiceEventArgs(string result)
{
_myVar = result;
}
}
In your UI layer do this
private void BtnClick_Click(object sender, RoutedEventArgs e)
{
Class1 c1 = new Class1();
c1.DataProcessed += c1_DataProcessed;
c1.HandleMethod(10);
}
void c1_DataProcessed(object sender, MyWebServiceEventArgs e)
{
TxtName.Text = e.MyProperty;
}
I brought the Silverlight CompletedEvent model to WinRT.
But you can simply live a happy life with async and await keywords.