How to make a function timedelay by 5 seconds

lorenzoid picture lorenzoid · Nov 22, 2011 · Viewed 15k times · Source

I'm trying to translate this into C# code:

Wait 5 seconds and then debit the bank account.

I've got a feeling I'm close... but this isn't working. Am I doing this the right way?

    public override void Process(BankAccount b, decimal amount)
    {
        DateTime present = DateTime.Now;
        DateTime addFiveSeconds = DateTime.Now.AddSeconds(5);

        if (present != addFiveSeconds)
        {
            this.Status = TransactionStatus.Pending;
        }
        else
        {
            b.Debit(amount);
            this.Status = TransactionStatus.Complete;
        }
    }

Answer

Oded picture Oded · Nov 22, 2011

Use Thread.Sleep(5000) in order to suspend a thread for 5 seconds, instead of your code - it has several logical errors.

present will be the value of DateTime.Now when that line is executed, and add30Seconds will be the value of DateTime.Now plus 5 seconds when that line is executed.

These variables will not update and will not change their values.

This means that present will never be == to add30Seconds.