I' trying to implement a fault recovery mechanism which will dispose a WCF connection on error (and then periodically attempt to reconnect and retry)
Essentially the relevant code is just
try
{
_client.DoSomthing();
}
catch
{
_client.Dispose();
}
The problem is that the above code runs inside a TPL dataflow block and must be thread safe. I'm having problems with the client being disposed while in use by other threads. I don't really want to put a lock around the whole thing as I then lose concurrent uploads and performance suffers.
I'm looking for some way to block new threads using the client but not try to dispose until I know any current calls are completed. And then to ensure that only one thread performs the dispose.
I'm imaging some mechanism along the lines of below (pseudo) code
using (var counter = new ThreadCounter())
{
try
{
if (!faulted)
_client.DoSomthing();
}
catch
{
faulted = true;
counter.BlockNewThreadsEntering()
if (counter == 1)
_client.Dispose();
}
}
Is there anything in the framework that would let me achieve this? Or any other suggestions?
Just follow the rule "one thread - one client". There's no reason to share database connections, http clients, service clients and so on between threads.
As a rule, all of these objects has a tiny state, and any efforts to minimize resource usage via sharing them is a headache, since you need to synchronize cross-thread access to prevent objects' state from corruption.
If your code considers system resources while creating new threads (thus, doesn't create 100 threads running on 4 CPU cores), one service client per thread isn't a problem.