假设我有一个活期银行账户,当余额不足时,它会自动从我的储蓄账户转账。所以,我写了下面的WCF代码:
//Servicer side:
[ServiceContract]
public interface IBankAccount
{
[OperationContract]
double withdraw(double amount);
[OperationContract]
double enquiry();
}
class BankAccountService:IBankAccount
{
public double enquiry()
{
return balance;
}
public double withdraw(double amount)
{
while (balance < amount)
{
transferMoreMoney();
}
deduct(amount);
return balance;
}
public void deduct(double amount)
{
System.Threading.Thread.Sleep(10000);
balance -= amount;
}
public void transferMoreMoney()
{
System.Threading.Thread.Sleep(10000);
balance += maximizeTransferAmount;
}
private static double balance;
private double maximizeTransferAmount = 100.0;
}
//Client side:
ServiceReference1.BankAccountClient client = new ServiceReference1.BankAccountClient();
while (true)
{
try
{
string tmpStr = Console.ReadLine();
if (tmpStr == "")
break;
double v0 = client.enquiry();
Console.WriteLine("Current balance is:{0}", v0);
double v1 = Convert.ToDouble(tmpStr);
Console.WriteLine("Amount withdrawn is:{0}", v1);
double v2 = client.withdraw(v1);
Console.WriteLine("Remaining balance is:{0}", v2);
}
catch (CommunicationException e)
{
Console.WriteLine(e.Message);
}
}问题是,当我有多个客户端调用同一服务时,余额可能为负。
此外,我仍然有其他客户端只运行余额查询,所以如果他们只查询,他们不应该等待,谁来确保这一点?
这只是一个例子,说明我需要什么。这个例子说明了我需要解决的技术问题,但不是真实的案例。我不能使用数据库,因为我的实际情况是需要在内存中进行高性能的实时计算,所以数据库不是一个选择。
更基本的是,当多个客户端调用共享相同数据的相同服务时,WCF服务中是否存在类似于“锁”的东西?
非常感谢。
发布于 2012-06-29 03:33:38
you must define behavior specific for your service wcf ( Singleton Instance Mode + Concurrency Mode Multiple)
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class BankAccountService: IBankAccount
{
}
Note : You can also define your behavior in config file发布于 2012-06-29 12:36:05
实际上您必须使用ConcurrencyMode.Single,并发模式single将对服务BankAccountService的所有调用进行排队,请求将一个接一个地执行。如果你选择ConcurrencyMode.Multiple,你必须自己实现线程锁。
https://stackoverflow.com/questions/11251467
复制相似问题