Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consuming WCF methods - abort / closing

I am consuming WCF in my ASP.NET MVC app and each of my methods contains try-catch-finally block. I am wondering if I am closing / aborting WCF call correctly. I know that "using" statement is not good for WCF calls.

Here is the sample metod

public int GetInvalidOrdersCount()
{
    OrderServiceClient svc = new OrderServiceClient();
    try
    {
        return svc.GetInvalidOrdersCount();
    }
    catch (Exception)
    {
        svc.Abort();
    throw;
    }
    finally
    {
        svc.Close();
    }
}
like image 782
303 Avatar asked Dec 08 '25 09:12

303


1 Answers

On msdn it shows an example of the 'proper' way to call:

CalculatorClient wcfClient = new CalculatorClient();
try
{
    Console.WriteLine(wcfClient.Add(4, 6));
    wcfClient.Close();
}
catch (TimeoutException timeout)
{
    // Handle the timeout exception.
    wcfClient.Abort();
}
catch (CommunicationException commException)
{
    // Handle the communication exception.
    wcfClient.Abort();
}

I usually follow this pattern when implementing clients. Except, you would probably also want to dispose with a using for the client:

using (CalculatorClient wcfClient = new CalculatorClient())
{
    try
    {
        return wcfClient.Add(4, 6);
    }
    catch (TimeoutException timeout)
    {
        // Handle the timeout exception.
        wcfClient.Abort();
    }
    catch (CommunicationException commException)
    {
        // Handle the communication exception.
        wcfClient.Abort();
    }
}
like image 155
Davin Tryon Avatar answered Dec 09 '25 23:12

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!