1

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?

Community
  • 1
  • 1
mafue
  • 1,858
  • 1
  • 21
  • 27

2 Answers2

0

The post you linked is talking about fairly general purpose solutions to the using statement problem with wxf proxy clients. So under generalized conditions there are many situations where I can imagine a race on the code you pasted. Especially a multi threaded situation sharing the same client.

Kenneth Ito
  • 5,201
  • 2
  • 25
  • 44
  • Wouldn't a shared client be defined in a some larger scope though ie. not inside a using block/using-block-alternative? – mafue Apr 13 '12 at 23:40
0

No satisfying answers, so the MSDN solution will have to do:

try
{
    ...
    client.Close();
}
catch (CommunicationException e)
{
    ...
    client.Abort();
}
catch (TimeoutException e)
{
    ...
    client.Abort();
}
catch (Exception e)
{
    ...
    client.Abort();
    throw;
}
mafue
  • 1,858
  • 1
  • 21
  • 27