问题描述
我有一个WCF服务,我来自多个客户端调用。我需要存储和管理全球的值。在我的服务,我有以下属性:
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();
}
使用WCF的我有限的知识,我想presume,我有一个单身的服务,事实证明我的私有变量是静态的,所有调用该服务将使用同一个对象。
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
我缺少的东西,使这项工作,我需要它的方式?我需要存储对象的某种缓存?任何帮助是极大的AP preciated。
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.
如果需要,我可以发布更多codeD。
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??
由于ConcurrencyMode设为单,太 - 你甚至不必担心并发访问的变量
Since the ConcurrencyMode is set to single, too - you don't even have to worry about concurrent access to the variable.
在另一方面 - 单用ConcurrencyMode =单是导致一个真的很慢的服务,它可能很快成为一个瓶颈 - 所以你可能要设定您的code以这样一种方式,它也将下工作ConcurrencyMode =多具有潜在的并发访问成员变量。
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.
这篇关于WCF静态变量获得复位每个调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!