1

假设我有一个活期银行账户,当余额不足时,它会自动从我的储蓄账户中转账。所以,我在下面写了 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 服务中是否存在类似于“锁定”的东西?

非常感谢。

4

2 回答 2

3

Actually you must be using ConcurrencyMode.Single, concurentcy mode single will queue all call to service BankAccountService and request will be executed one after other. If you go for ConcurrencyMode.Multiple you yourself have to implement thread lock.

于 2012-06-29T04:36:04.637 回答
3
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-28T19:33:38.197 回答