Question

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;
        }
    }
Was it helpful?

Solution

I think above answer has flaw, it hangs up the main thread , in most case, it is dangerous. You should start a new thread for this delay task, in the thread proc, sleep 30 seconds and then do the work in second thread.

OTHER TIPS

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.

SO your requirement it wait 30 seconds and then debit? If so, look at the Timer class. You can set the interval to 30 seconds, and when triggered perform your action.

http://www.dijksterhuis.org/using-timers-in-c/

30 seconds does seem an awful long time though to wait? Is this a coursework requirement?

There's nothing actually waiting in your code. You're immediately executing the check and it will always be true. In fact, unless you get extremely lucky, you'll almost never hit that exact time.

You could use a timer with this.

var completed = false;
var timer = new System.Timers.Timer(30 * 1000);
timer.Elapsed += (o,e) => 
   {
       b.Debit(amount);
       completed = true;
       this.Status = TransactionStatus.Complete;
   };
timer.Start();
this.Status = TransactionStatus.Pending;

while (!completed) ;

NOTE There's no error-checking if the debit hangs or times out.

You can use this code too:

DateTime present = DateTime.Now;
DateTime addFiveSeconds = DateTime.Now.AddSeconds(10);

while (DateTime.Now.TimeOfDay.TotalSeconds <= addFiveSeconds.TimeOfDay.TotalSeconds)
{
    this.Status = TransactionStatus.Pending;                
}  
b.Debit(amount);
this.Status = TransactionStatus.Complete;

add to start of code:

using

System.Threading;                // allows use of sleep time

In your code insert:

Thread.Sleep(5000);             // Pause 5 seconds, where you need, delay 5 seconds
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top