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?