Ejemplo n.º 1
0
        public void Transfer()
        {
            object _lock1, _lock2;

            if (FromAccount.Id < ToAccount.Id)
            {
                _lock1 = FromAccount;
                _lock2 = ToAccount;
            }
            else
            {
                _lock1 = ToAccount;
                _lock2 = FromAccount;
            }
            Console.WriteLine($"{Thread.CurrentThread.Name} trying to acquire lock on {((Account)_lock1).Id.ToString()}");
            lock (_lock1)
            {
                Console.WriteLine($"{Thread.CurrentThread.Name} acquired lock on {((Account)_lock1).Id.ToString()}");
                Console.WriteLine($"{Thread.CurrentThread.Name} suspende for 1 sec");
                Thread.Sleep(1000);
                Console.WriteLine($"{Thread.CurrentThread.Name} back on action and trying to acquire lock on {((Account)_lock2).Id.ToString()}");
                lock (_lock2)
                {
                    Console.WriteLine($"{Thread.CurrentThread.Name} acquired lock on {((Account)_lock2).Id.ToString()}");
                    FromAccount.Withdraw(AmountToTransfer);
                    ToAccount.Deposit(AmountToTransfer);
                    Console.WriteLine($"{Thread.CurrentThread.Name} Transfered {AmountToTransfer} From {FromAccount.Id} to {ToAccount.Id}");
                }
            }
        }
        public void Transfer(decimal amount)
        {
            Console.WriteLine($"Initializing transfer #{FromAccount.Id}:{FromAccount.Balance} -{amount}-> #{ToAccount.Id}:{ToAccount.Balance}");
            using (var transaction = Services.AccountRepository.BeginTransaction())
            {
                FromAccount = FromAccount.Withdraw(amount, Services.AccountRepository.Persist);
                ToAccount   = ToAccount.Deposit(amount, Services.AccountRepository.Persist);

                transaction.Commit();
                Console.WriteLine("End of transaction.");
            }
        }
Ejemplo n.º 3
0
    public TransactionResult Execute()
    {
        TransactionResult result = FromAccount.Withdraw(this);

        if (result == TransactionResult.SUCCESS)
        {
            return(ToAccount.Deposit(this));
        }
        else
        {
            return(result);
        }
    }