1

I've created my own Wrapper for WCF calls according to What is the best workaround for the WCF client `using` block issue?

public delegate void UseServiceDelegate<T>(T proxy); 

public static class Service<T> 
{ 
    public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(""); 

    public static void Use(UseServiceDelegate<T> codeBlock) 
    { 
        IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel(); 
        bool success = false; 
        try 
        { 
            codeBlock((T)proxy); 
            proxy.Close(); 
            success = true; 
        } 
        finally 
        { 
            if (!success) 
            { 
                proxy.Abort(); 
            } 
        } 
     } 
} 

I can call it with:

Service<IOrderService>.Use(orderService => 
{ 
    orderService.PlaceOrder(request); 
}); 

How can I make this for asynchronous WCF calls?

What I've already tried is:

public delegate Task UseAsyncServiceDelegate<T>(T proxy);

public static async Task UseAsync(UseAsyncServiceDelegate<T> codeBlock)
{
    IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
    bool success = false;
    try
    {
        await codeBlock((T)proxy);
        proxy.Close();
        success = true;
    }
    finally
    {
        if (!success)
        {
            proxy.Abort();
        }
    }
}

But it is not working.

Community
  • 1
  • 1
Pinzi
  • 293
  • 6
  • 18
  • How is this an improvement over `using`? You could use the same code with the proxy generated by svcutil or VIsual Studio. You didn't have to work with the channel directly. This way you wouldn't have to reimplement the async methods – Panagiotis Kanavos Mar 24 '17 at 08:08
  • In any case, check the proxy's generated code. You'll see that the generated async methods actually call similar methods on the *strongly typed* channel. – Panagiotis Kanavos Mar 24 '17 at 08:15
  • As far as I understand using should be avoided in Wcf clients. The second problem I'd have with using: I would like to implement an exception handling in my Service.Use and Service.UseAsync functions – Pinzi Mar 24 '17 at 08:15
  • very good tip, I'll check the generated functions – Pinzi Mar 24 '17 at 08:16
  • Avoided as is, yes. That doesn't mean you should avoid the *proxy*. It means you should take care how you close the proxy. Your code, *unlike* the linked question uses the base `IClientChannel`, instead of the strongly-typed `IOrderService` – Panagiotis Kanavos Mar 24 '17 at 08:16
  • What would be a better solution where I can use async calls and implement a reusable exception handling? – Pinzi Mar 24 '17 at 08:42

0 Answers0