开发者

WCF: Make all calls wait when one specific interface is being called

I have a WCF service with quite a few interfaces which only read data. There is however one interface that reloads data from the database and reinitialises some dictionaries. While this interface "Reload" is running I effectively want all other calls to be put "on hold" as they would read data of an unknown state (as I am using per-call)

[ServiceContract]
public interface IMyObject
{
    [OperationContract] 
    string Reload();
    [OperationContract]
    string Read1();
    [OperationContract]
    string Read2();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyObject : IMyObject
{
    public string Reload() { //Takes 5-10secs, called twice a day  }
    public string Read1() {  //Wait for Reload() to finish if it's running}
    public string Read2() {  //Wait for Reload() to finish if it's running} 
}

Is this possible in开发者_开发技巧 WCF? Or is there a best practise way around this problem?


I believe if you play with the ConcurrencyMode and set it to single you can achieve what you want.

Having said that, I had achieved what you want having a flag on my services. If you set a static flag other calls can check for that flag and do what ever you want them to do


Suggest you to:

  1. Change InstanceContextMode.PerCall to InstanceContextMode.Single
  2. Then add ConcurrencyMode = ConcurrencyMode.Multiple (will allow more than 1 execution in a time)
  3. In your MyObject implementation manually deal with concurrency. Use simple lock or advanced mechanics, like ReaderWriterLockSlim.

Implementation with lock is as follows:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
class MyObject: IMyObject
{
    private readonly object lockObject = new object();
    public string Reload()
    {
        lock (lockObject)
        {
            // Reload stuff
        }
    }
    public string Read1()
    {
        lock (lockObject)
        {
            // Read1 stuff
        }
    }

    public string Read2()
    {
        lock (lockObject)
        {
            // Read2 stuff
        }
    }
}

Drawbacks, that it won't allow you to call simultaneously Read1 and Read2. If you need this functionality, use ReaderWriterLockSlim instead of lock.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜