Static Methods / Fields and WCF

can safely use static methods / classes in WCF because WCF creates a new thread for each user, so if I have a static variable

public static int = 5

and if two clients try to change it at the same time, will one of them change it for the other?

thank...

+3
source share
3 answers

Well, someone can change the static field and they will see the last value set depending on the scheduling of threads and processors. However, for a safe implementation, you must define another static object and use it to lock and grant your access to the variable through the 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;
      }
   }
}

-, , Service Host WCF .

IIS , , .

- / . HttpContext.Current.Server( ASP.NET).

+5

.

. "", .

, , :

void Foo()
{
    filed++;
    Bar(field);
}

, lock, :

void Foo()
{
    lock(fieldLock)
    {
         filed++;
         Bar(field);
    } 
}
+4

I assume that you are asking if two clients have called a service method that changes the static field on the server, will this work? I'm not sure what you are trying to execute, but if you want to share this value, you need to do some work to make it thread safe (blocking).

0
source

Source: https://habr.com/ru/post/1762302/


All Articles