Example #1
0
        public static bool TransferMoney(Account starting, Account destination, float amount)
        {
            if (amount > max_transfer)
            {
                MessageBox.Show("Amount exceeds maximum single transaction limit.");
                return(false);
            }

            //Attempt to make changes to the account balance itself thread safe.

            Mutex mutex = new Mutex();

            mutex.WaitOne();
            //Critical Section - Begin
            bool transferComplete = false;

            using (var context = new AccountManagerContext()) {
                destination.Balance += amount;
                starting.Balance    -= amount;

                if (starting.GetType() == typeof(SavingsAccount))
                {
                    SavingsAccount s = (SavingsAccount)starting;
                    s.WithdrawalsThisMonth++;
                }
                context.Entry(starting).State    = System.Data.Entity.EntityState.Modified;
                context.Entry(destination).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();
                transferComplete = true;
            }
            //Critical Section - End
            mutex.ReleaseMutex();
            return(transferComplete);
        }
Example #2
0
        public static bool CreditAccount(Account account, float creditAmount)
        {
            if (creditAmount > max_transfer)
            {
                MessageBox.Show("Amount exceeds maximum single transaction limit.");
                return(false);
            }

            //Attempt to make changes to the account balance itself thread safe.

            Mutex mutex = new Mutex();

            mutex.WaitOne();

            //Critical Section - Begin
            bool balanceChanged = false;

            using (var context = new AccountManagerContext())
            {
                account.Balance += creditAmount;
                context.Entry(account).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();
            }
            balanceChanged = true;
            //Critical Section - End

            mutex.ReleaseMutex();
            return(balanceChanged);
        }