我在WCF服务中有两个方法说
Method1()
{
_currentValue = 10;
}
Method2()
{
return _currentValue;
}
Run Code Online (Sandbox Code Playgroud)
我有一种情况,我需要在Method1()中设置一个值,并在Method2()中读取它.
我尝试使用static变量public static int _currentValue,我能够读取Method2()中Method1()中设置的值.
但问题是,我希望这个变量像每个请求的单独实例变量一样做出反应.即,现在下面是问题
浏览器1:
- Method1() is called
=> sets _currentValue = 10;
- Method2() is called
=> returns _currentValue = 10;
Run Code Online (Sandbox Code Playgroud)
浏览器2:
- Method2() is called
=> returns _currentValue = 10;
Run Code Online (Sandbox Code Playgroud)
实际上,值集是浏览器1是静态的,因此在浏览器2中检索相同的值.
我想要实现的是变量应该像每个请求的新实例(从每个浏览器调用时).在这种情况下我应该使用什么?会话?
您将需要某种关联机制,因为您有两个完全不同的会话调用不同的方法。所以我建议使用双方都知道的私钥。
我不太可能知道这个密钥是什么,因为我无法真正从你的问题中收集到任何信息,所以只有你知道这一点,但简单的事实是你将需要相关性。现在,一旦您确定了他们可以使用什么,您就可以执行类似的操作。
public class SessionState
{
private Dictionary<string, int> Cache { get; set; }
public SessionState()
{
this.Cache = new Dictionary<string, int>();
}
public void SetCachedValue(string key, int val)
{
if (!this.Cache.ContainsKey(key))
{
this.Cache.Add(key, val);
}
else
{
this.Cache[key] = val;
}
}
public int GetCachedValue(string key)
{
if (!this.Cache.ContainsKey(key))
{
return -1;
}
return this.Cache[key];
}
}
public class Service1
{
private static sessionState = new SessionState();
public void Method1(string privateKey)
{
sessionState.SetCachedValue(privateKey, {some integer value});
}
public int Method2(string privateKey)
{
return sessionState.GetCachedValue(privateKey);
}
}
Run Code Online (Sandbox Code Playgroud)