如何使函数延时 5 秒
我正在尝试将其转换为 C# 代码:
等待 5 秒,然后从银行帐户中扣除。
我有一种感觉,我已经很接近了……但这行不通。我这样做的方式正确吗?
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 Thread.Sleep(5000) 来将线程挂起 5 秒,而不是您的代码 - 它有几个逻辑错误。
当执行该行时,
present
将是DateTime.Now
的值,add30Seconds
将是DateTime.Now< 的值/code> 当该行执行时加上 5 秒。
这些变量不会更新并且不会改变它们的值。
这意味着
present
将永远==
到add30Seconds
。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 ofDateTime.Now
when that line is executed, andadd30Seconds
will be the value ofDateTime.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==
toadd30Seconds
.我认为上面的答案有缺陷,它挂起了主线程,在大多数情况下,这是危险的。
您应该为此延迟任务启动一个新线程,在线程过程中,睡眠 30 秒,然后在第二个线程中执行工作。
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.
那么您的要求是等待 30 秒然后扣款?如果是这样,请查看 Timer 类。您可以将间隔设置为 30 秒,并在触发时执行您的操作。
http://www.dijksterhuis.org/using-timers-in-c/
30 秒似乎等待的时间很长?这是课程作业要求吗?
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.
NOTE There's no error-checking if the debit hangs or times out.
您也可以使用此代码:
You can use this code too:
添加到代码开头:
使用
在代码中插入:
add to start of code:
using
In your code insert: