How to: Callback function with WCF

 

The goal is to inform the client that the server process has progressed:

Situation: You have to update a lot of data on the server. You can use a web Service which will update your database. Each time a field is updated, the server can inform the client with the callback function.

Code on the Server side:

Add an interface :

public interface IProgress
{
[OperationContract(IsOneWay = true)]
void Update(int value);
}

Call the methode when you want to inform the client:

public boolean TransferMoney(int[] values)
{
IProgress iProgress = OperationContext.Current.GetCallbackChannel<IProgress>();
int val;
foreach (val in values)
{
iProgress.Update(val);
UpdateData(val); //Update the database
}
return true;
}

And change your Service Contract:

[ServiceContract(CallbackContract=typeof(IProgress), SessionMode=SessionMode.Required)]

Code on the Client side:

Create the class which implements the Interface and add the method which will be called by the server

class Handler : IBankingServiceCallback
{
public void Update(int value)
{
Console.WriteLine(“DataBase updated with: ”+value);
}
}

Change the call of the proxy with the InstanceContext in Parameter:

MyProxy proxy = new MyProxy (new InstanceContext(new Handler()));