Search code examples
c#wcfcallbackwcf-callbacks

WCF Callback - Synchronous execution


I'm trying to implement WCF Callback. When I call the callback method on my service side, it executes asynchronously. Is there a way to wait for the callback method to finish execution before the service method steps on to the next statement, without returning a value to the service from callback?

//Server Side
public interface ICallback
{        
    [OperationContract]
    void Oncallback1(string str);
    [OperationContract]
    int Oncallback2(string str);
}    
[ServiceContract(CallbackContract = typeof(ICallback))]
public interface IServiceContract
{
    [OperationContract]
    void Method1();      
}

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class MycallbackService : IServiceContract
{        

    public void Method1()
    {               
        ICallback objIcallback = OperationContext.Current.GetCallbackChannel<ICallback>();
        Thread.Sleep(5000);
        objIcallback.Oncallback1(obj1);
        Console.WriteLine("calling callback2");
        Console.WriteLine(objIcallback.Oncallback2("2"));
        Console.WriteLine("Service Execution over!");
    }
}
//Client Side
[CallbackBehavior]
public class callbackClient : ICallback
{
    public void Oncallback1(CallbackService.EventInfo obj)
    {
        Thread.Sleep(5000);
        Console.WriteLine("Callback 1");

    }
    public int Oncallback2(string str)
    {
        Thread.Sleep(5000);
        Console.WriteLine("Callback 4");
        return 2;
    }
}

Here the statement "Console.WriteLine("calling callback2");" is executed before the callback1 method finishes. Whereas it waits till callback2 finishes.


Solution

  • I believe this is because of difference of callback method`s return type:

    void Oncallback1(string str);
    int Oncallback2(string str);
    

    Oncallback1 returns nothing so by default it is a IsOneWay = true fire-and-forget operation. On the other hand Oncallback2 defaults to IsOneWay = false