Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to dispose wcf object with async pattern

Tags:

Supposing I start off with the synchronous version:

 using(var svc = new ServiceObject()) {
     var result = svc.DoSomething();
     // do stuff with result
 }

I wind up with

var svc = new ServiceObject();
svc.BeginDoSomething(async => {
    var result = svc.EndDoSomething(async);
    svc.Dispose();
    // do stuff with result
},null);

1) Is this the correct place to call Dispose()?

2) is there a way to use using() ?

like image 765
Jimmy Avatar asked Jun 17 '09 19:06

Jimmy


1 Answers

From Rotem Bloom's blog: http://caught-in-a-web.blogspot.com/2008/05/best-practices-how-to-dispose-wcf.html

Best Practices: How to Dispose WCF clients

Use of the using statement (Using in Visual Basic) is not recommended for Dispose WCF clients. This is because the end of the using statement can cause exceptions that can mask other exceptions you may need to know about.


using (CalculatorClient client = new CalculatorClient())
{
...
} // this line might throw

Console.WriteLine("Hope this code wasn't important, because it might not happen.");

The correct way to do it is:
try
{
    client.Close();
}
catch (CommunicationException)
{
    client.Abort();
}
catch (TimeoutException)
{
    client.Abort();
}
catch
{
     client.Abort();
     throw;
}
like image 110
Boris Modylevsky Avatar answered Sep 29 '22 15:09

Boris Modylevsky