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:
- Change InstanceContextMode.PerCall to InstanceContextMode.Single
- Then add ConcurrencyMode = ConcurrencyMode.Multiple (will allow more than 1 execution in a time)
- 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.
精彩评论