This example show you how a client can access a service operation asynchronously in a easy way.
First, I created a WCF Service Library in VS 2008
using System;
using System.ServiceModel;
using System.Diagnostics;
[ServiceContract]
interface ICalculator
{
[OperationContract]
int Add(int number1,int number2);
[OperationContract]
int Subtract(int number1,int number2);
[OperationContract]
int Multiply(int number1,int number2);
[OperationContract]
int Divide(int number1,int number2);
}
class Calculator : ICalculator
{
public int Add(int number1,int number2)
{
return number1 + number2;
}
public int Subtract(int number1,int number2)
{
return number1 - number2;
}
public int Multiply(int number1,int number2)
{
return number1 * number2;
}
public int Divide(int number1,int number2)
{
return number1 / number2;
}
}
Then run the Service Test, if you add a Service Reference to the WCF Service will not generate a event-driven asynchronous calling. You need run the ServiceModel Metadata Utility Tool (Svcutil.exe) tool with both the /async and the /tcv:Version35 command options together as shown in the following command.
svcutil http://localhost:8731/Design_Time_Addresses/SimpleCalculatorService/Calculator/mex /a /tcv:Version35
This generates, in addition to the synchronous and standard delegate-based asynchronous operations, a WCF client class that contains:
Then in your client, you just need to create a method to handle the CompletedEvent.
private void button1_Click(object sender, EventArgs e)
{
// AddAsync
CalculatorClient client = new CalculatorClient();
int value1 = 100;
int value2 = 15;
client.AddCompleted += new EventHandler<AddCompletedEventArgs>(AddCallback);
client.AddAsync(value1, value2);
Console.WriteLine("Add({0},{1})", value1, value2);
}
private void AddCallback(object sender, AddCompletedEventArgs args)
{
Text = "Sum = " + args.Result;
}
Enjoy coding! You can download the code from Here
More details from http://msdn.microsoft.com/en-us/library/ms730059.aspx