This is one of the Windows Communication Foundation mysteries. I still don't know why the code below does not (really) work:
for (int i = 0; i < 100; i++)
IMyService proxy = new ChannelFactory("MyService").CreateChannel();
// Without this line the proxy invocation fails on the 10th DoSomething() method call
proxy.Close() is commented, in the code above, the WCF throws the TimeoutException on the 11th proxy invocation (the variable i == 10). So the first 10 requests works properly and the 11th one throws the exception:
A first chance exception of type 'System.TimeoutException' occurred in mscorlib.dll
Additional information: The open operation did not complete within the allotted timeout of 00:01:00. The time allotted to this operation may have been a portion of a longer timeout.
My first thought when I figured out that it is caused by lack of the Close() method call was: Why the hell I have to close the proxy?
I tried to find out why, but the only reason I see is this one: WCF session is managed by client proxy lifetime so when you close the proxy it sends such information to serever so the remote service could be released. But my service is not session-bound so I think I don't need to close it.
I tried one more thing: I added
GC.Collect() instead of the
proxy.Close() and everything worked fine - destroying proxy with GC closes it.
This behavior looks weirdy to me, as it can occur not on the 11th proxy invocation but during the 13, 25 or any other if the Garbage Collector is involved. This can cause mistakes and application strange behavior.
Anyway: why do we really need to close the service proxy? I am still looking for the answer - I'll post it when I find it.