Udostępnij za pośrednictwem


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()));

Comments

  • Anonymous
    June 19, 2007
    The comment has been removed

  • Anonymous
    June 19, 2007
    That's what I needed: DuplexChannelFactory<IServer> channelFactory = new DuplexChannelFactory<IServer>(new InstanceContext(new Handler()), netTcpBinding, "net.tcp://localhost:6000/server");            IServer server = channelFactory.CreateChannel();

  • Anonymous
    January 22, 2008
    Hi, What is the best way of using WCF and providing feedback to the client using aspx as the UI? Thanks

  • Anonymous
    September 14, 2008
    The comment has been removed