1

This is a follow up question to this question:

What could be causing a "Cannot access a disposed object" error in WCF?

I also encountered the "Cannot access a disposed object" exception after trying to reopen a connection with a client after the connection was closed. I was doing this:

try
{
   if (!(client.State == CommunicationState.Opened) && !(client.State == CommunicationState.Opening))
   {
         await Task.Run(() => client.Open());
   }
   ...
finally
{
    client.Close();
}

Upon re entering the code, was the exception thrown again.

The accepted answer in the linked question suggests either:

1) Doing something like client = new WebServiceClient() each time there's a need to call the web service.

2) Implementing IDisposable and dispose of the client in the Dispose method by closing it only there, but it means leaving the connection open all the time..

Is there a convention on how to handle this situation?

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
  • Is recreating the client an issue in your scenario? Is that code CPU bound / memory bound? If not, recreate the client for a call or calls on a thread. You better not re-use a client that is in a faulted state, as it is un-likely that calling Close and Open will clear all error conditions. – rene May 25 '19 at 07:07
  • @rene but it seems really odd that a client needs to be recreated like that each time.. that's how it was intended to be used? I don't understand why would closing the connection also dispose of the entire client – CodeMonkey May 25 '19 at 07:35
  • An Entity Framework DataContext has the same usage guidance so it doesn't come over as odd or a one-of case at all. One of the problems might be that the WCF client is so much of an abstraction that it doesn't handle the actual OS recourses like network handles correctly but I didn't dig through the implementation to verify or seek evidence of that assumption. Restricting my implementations to recreate instead of re-use have never led me to problems I couldn't solve or were to vague to figure out a solution. – rene May 25 '19 at 07:45

0 Answers0