Saturday, 22 September 2012

Quickstart Task-based WCF service

This post shows you how to create a task based WCF Service using Visual Studio 2012.

1. Create a new project using File > New > Project.
In the wizard select the Visual C# \ WCF \ WCF Service Application

2. Alter the service definition to return Task
public async Task<string> GetData(int value)   
   Thread.Sleep(4); // Simulate a slow call...  
   return await Task.Factory.StartNew( 
       () => string.Format("You entered: {0}", value));  

You will also need to alter the interface to return Task also.

We use a sleep to simulate a lengthy operation and make the asynchronous behavior very obvious, this would not exist in real code.

3. Right click the solution select Add > New Project
In the wizard select Visual C# \ Windows \ WPF Application

4. Right click the WPF application
Select Add Service Reference
Click Discover, select Service1
Click Advanced, ensure 'Allow generation of asynchronous operations' and 'Generate task-based operations' are enabled.

5. Edit the MainWindow.xaml for the WPF application, make it look like the following :-
<Window x:Class="WpfApplication1.MainWindow"  
    Title="MainWindow" Height="100" Width="200">  
    <RowDefinition />  
    <RowDefinition />  
  <TextBlock x:Name="txtMessage" Grid.Row="0">Service Not Yet Called</TextBlock>  
  <Button x:Name="btnAsync" Click="btnAsync_Click" Grid.Row="1">Call Service</Button>  

6. Now implement the buttom event handler in the MainWindow.xaml.cs
async private void btnAsync_Click(object sender, RoutedEventArgs e)
  using(var client = new ServiceReference1.Service1Client("BasicHttpBinding_IService1"))
    txtMessage.Text = await client.GetDataAsync(5);

7. Now right click the solution and select Set Startup projects
Select 'Multiple Strtup projects' and set both projects to 'Start'.

8. Now press F5 to launch the debugger

The WCF service will be started and hosted by IISExpress, you will see the root folder listing appear in your browser.
At the same time the client will be launched and you will see the WPF user interface.
Click the 'Call Service' button and you should see the message change to 'You entered: 5' indicating a successful service call!
To prove your client really is making an async call and not blocking the UI thread, try moving the window with the mouse after clicking the 'Call Service' button.

Well done! You've created your first Task based WCF service...

No comments:

Post a Comment