I have a WCF service that I am calling from multiple clients. I need to store and manage a value globally. On my service I have the following attributes:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
In my service I have something similar to this:
private static int counter;
public void PrintCounter()
{
counter++;
StreamWriter sw = new StreamWriter(@"C:\outFile.txt", true);
sw.WriteLine("Counter: " + counter);
sw.Close();
}
With my limited knowledge of WCF, I would presume that I have a Singleton service and the fact that my private variable is static, that all calls to the service would use the same object.
However, when I look at my log output, I see the following:
Counter: 1
Counter: 1
What I expected to see would be:
Counter: 1
Counter: 2
Am I missing something to make this work the way I need it to? Do I need to store objects in some sort of cache? Any help is greatly appreciated.
I can post more coded if needed.
Since it's a singleton service, e.g. only one instance will ever exists of it, why don't you make this a regular class member variable??
Since the ConcurrencyMode is set to single, too - you don't even have to worry about concurrent access to the variable.
On the other hand - singleton with ConcurrencyMode=Single is a recipe for a really really slow service which might become a bottleneck quickly - so you might want to program your code in such a way that it would also work under ConcurrencyMode=Multiple with potentially concurrent access to the member variable.
I assume you only have one server, so this isn't due to load-balancing.
Static data should stick around, unless IIS is recycling the app for some reason?
BTW, you should really use
Interlocked.Increment
for that, but this shouldn't cause the problem you are seeing (unless you are under massive load, and you are seeing things like