Thursday, July 02, 2009

WCF thread safety in 25 lines of code

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
public class ThreadSafeService : IServiceContract
{
private int counter;

[MethodImpl(MethodImplOptions.Synchronized)]
public void IncrementCounter(int amount)
{
Mutex m = new Mutex(false);
try
{
Monitor.Enter(this);
m.WaitOne();
lock (this)
{
Interlocked.Add(ref counter, amount);
}
}
finally
{
m.ReleaseMutex();
Monitor.Exit(this);
}
}
}

I dare to say that familiarity with every technique used in this sample would make you comfortable in dealing with WCF multithreading and throughput issues.

1 comment:

Chris Barrow said...

Sweet fancy moses that's awesome!!


© 2008-2013 Michael Goldobin. All rights reserved