views:

435

answers:

2

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.

+2  A: 

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.

marc_s
I removed the [ServiceBehavior] attribute and it does the same thing.I should note that I am calling my service from 2 different browsers in both cases.
Brandon
well, if you don't have a singleton anymore, then each incoming request gets a brand-spanking new instance of the service class, which is disposed after it's done. Nothing "lingers" around in that case for sure.
marc_s
My scenario was found while testing session management. When a user logs in, we give them a session GUID that is embedded into an authentication token. The session times out after so many minutes. We were storing it as a static list of GUID's, but with each WCF service session, they get a new session list. I am starting to think it is wiser to push this session information off to some sort of datastore like memcached.
Brandon
A: 

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

10003120
10003121
10003121
10003121
10003122
Marc Gravell