如何使功能延迟5秒
问题描述:
我正在尝试将其转换为C#代码:
I'm trying to translate this into C# code:
等待5秒钟,然后从银行帐户中扣款.
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;
}
}
答
我认为以上答案有缺陷,它使主线程挂掉了,在大多数情况下,这很危险. 您应该为此延迟任务启动一个新线程,在线程proc中睡眠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.