静态方法/字段和WCF字段、静态、方法、WCF

2023-09-06 13:13:38 作者:很nice

可以使用静态方法/类的安全在WCF中原因在于WCF为每个用户创建一个新的线程,这样的事实,如果我将有一个静态变量

can use static methods/ classes safely in WCF due to the fact that WCF creates a new thread for each user, so if i'll have a static variable

public static int = 5

如果两个客户端会试图同时改变它,将其中一人将能够改变它为其他?

and if two clients will try to change it simultaneously, will one of them will be able to change it for the other?

谢谢...

推荐答案

那么任何人都可以修改静态字段的时候,就会看到这取决于线程和处理器调度最新的设定值。然而,对于安全的实现,你应该定义一个比较静态的对象,并用它来锁定,并通过静态属性提供您访问的变量。

Well anyone can modify static field and they will see the latest value set depending upon thread and processor scheduling. However for safe implementation you should define one more static object and use it for lock and provide your access to variable through static property.

private static object lockObject = new object();
private static int _MyValue = 0;
public static int MyStaticValue{
   get{
      int v = 0;
      lock(lockObject){
         v = _MyValue;
      }
      return v;
   }
   set{
      lock(lockObject){
         _MyValue = value;
      }
   }
}

这是线程安全的,以及为每个线程和每个实例只要WCF服务主机保持进程共享活着。

This is thread safe as well as is shared for every threads and every instance as long as Service Host of WCF keeps process alive.

在IIS或任何这样的过程模型,如果进程被回收,你将失去最后一个静态值。

In IIS or any such process model, if process is recycled, you will loose the last static value.

您应该使用某种类型的服务器/应用程序级别的商店。例如HttpContext.Current.Server(在ASP.NET中)。

You should use some sort of server/application level store. e.g. HttpContext.Current.Server (in case of ASP.NET).