다음을 통해 공유


Windows 8 – style applications and WCF services

If you get yourself a developer account, you will be able to create Windows 8 – style applications with Visual Studio 2012. One of the first things I tried was to create a client for a WCF service.
I created a simple application, with a command button and a textbox, and then a new project of type WCF Application. Using just the default contract of the WCF service template, I added a reference to the service, instantiated the proxy in the client application and then tried to call the GetData method.
First surprise, the proxy only has async methods:

As per the method’s documentation, it can be used as:

 str x = await sc.GetDataAsync(int value) 
 

And the method itself, if we look at the declaration, returns

 System.Threading.Tasks.Task<string> 
 

In order to use the new await keyword, introduced in .NET 4.5, we need to be in an async method. You can find more information about asynchronous programming in VS 2012 on MSDN:
https://msdn.microsoft.com/en-us/library/hh191443(v=VS.110).aspx

So, assuming I am doing this proxy initialization and method call in Button_Click, the code needs to look like this:  

 private async void Button_Click_1(object sender, RoutedEventArgs e) 
 { 
 ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client(); 
 string str = await sc.GetDataAsync(10); 

This will prevent the application from freezing until the method returns from the service. You can test this by adding a System.Threading.Thread.Sleep(5000); in the GetData method of the service, and you will see that the other controls of your application remain responsive.

Further on, let’s say that you don’t want to have an async method, and you insist on your application remaining frozen until the work on the service side is done. Maybe you secretly believe that this approach will give you special super-powers, or maybe you have some other valid arguments for doing so. Anyway, if you want to do that, you only have to look at the method’s signature and see the return type:

 System.Threading.Tasks.Task<string>

You can then go on like this, retrieving a Task<string> object from the proxy method and then reading the Result property, which will contain the actual string returned by the service’s GetData.

 Task<string> s = sc.GetDataAsync(10);
this.TextBox1.Text = s.Result; 

Sure enough, you will be able to enjoy your popcorn while staring at the locked screen for the next 5 seconds, while the WCF service does it’s Sleep(5000) routine.