How to find out how many clients are calling my WCF service function
I am writing a program to test the performance of a WCF service under a high concurrency circumstance.
On the client side, I run many threads to call a WCF service function that returns a long list of data objects.
On the server side, in this function being called by my client, I need to know the number of clients calling this function.
For this I set a counter variable. At the beginning of the function, I add a counter by 1, but how can I decrease it after the function has returned a result ?
int clientCount=0;
public DataObject[] GetData()
{
Interlocked.Increment(ref clientCount);
List<DataObject> result = MockDb.GetData();
return result.ToArray();
Interlocked.Decrement(ref clientCount); //can't run to here...
}
I've seen a way in C ++.
Create a new class named counter.
In the constructor of the counter class, increment the variable. And shrink it down in the destructor.
In the function, create a counter object to be called by its constructor. And after the function returns, its destructor will be called.
Like this:
class counter
{
public:
counter(){++clientCount; /* not simply like this, need to be atomic*/}
~counter(){--clientCount; /* not simply like this, need to be atomic*/}
};
...
myfunction()
{
counter c;
//do something
return something;
}
In C # I think I can do it with the following codes, but not sure.
public class Service1 : IService1
{
static int clientCount = 0;
private class ClientCounter : IDisposable
{
public ClientCounter()
{
Interlocked.Increment(ref clientCount);
}
public void Dispose()
{
Interlocked.Decrement(ref clientCount);
}
}
public DataObject[] GetData()
{
using (ClientCounter counter = new ClientCounter())
{
List<DataObject> result = MockDb.GetData();
return result.ToArray();
}
}
}
I am writing a counter class that implements the IDisposable interface . And put my function codes in with a block . But it looks like it's not that good. No matter how many threads I run, the clientCount variable is much less than the number of threads.
Any guidance would be appreciated.
a source to share
Take a look at the different layers used by WCF. You can connect to one of them.
For example add IDispatchMessageInspector to EndpointBehavior:
public class ConsoleOutputMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
Console.WriteLine("Starting call");
// count++ here
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
// count-- here
Console.WriteLine("Returning");
}
}
More details here: http://weblogs.asp.net/paolopia/archive/2007/08/23/writing-a-wcf-message-inspector.aspx
See how to extend WCF here: http://msdn.microsoft.com/en-us/magazine/cc163302.aspx#S6
a source to share