As mentioned elsewhere, this code has the potential for a race condition:
// do stuff with client, catch exceptions
if (client.State == CommunicationState.Faulted)
{
client.Abort();
}
else
{
// I hope nothing happened since I checked for a faulted state
client.Close();
}
... or does it?
As a State Machine, under what circumstances would a client go into a faulted state in-between attempts to check its state and subsequently close it? Even after several minutes/hours/days.
I tried the following simple-minded test, to rule out losing connection to the server:
- put a break point at the if statement. I see client.State == opened. Step on.
- Kill the WCF server process. Step on.
- Client.Close() executes without a problem.
As a second test, rather than kill the server process, I waited for the ReceiveTimeout
to elapse. Then I waited an extra minute. Then I stepped on to Client.Close(). No problem.
Can the client go into a faulted state without any input from me and, if not, is there really potential for a race condition?
EDIT: Perhaps this is too general, but I was looking for general guidance. The reason I asked this question is because I need to get some web developers to use WCF instead of obsolete web service technology. Ideally, I would like to be able to tell them that they can't use using
but they can use try-catch-finally
as long as the finally checks for faulted state and aborts rather than closing (I think this approach is easy to understand and adopt - important, given that there is already quite a lot to learn when you start WCF).
Then I started thinking about the race condition issue and couldn't think of an example where one might occur, given that the intent is to close the client, which you would not do if it was being used elsewhere (ie. shared between programs or threads in the current program.)
So, the question remains, is there potential for a race condition in this scenario and can anyone show me some code that demonstrates it?