开发者

static methods/fields and 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,开发者_JAVA百科 will one of them will be able to change it for the other?

thanks...


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;
      }
   }
}

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.

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

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


There'll be a race condition here.

The static field will be shared in all service instances. If two instances will access it "simultaneously" you may get unpredicted result.

For example, if two threads will run the code with no synchronization a non deterministic result might appear:

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

It can be solved using lock for example:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜