Thread.Sleep()和构造函数修改?

时间:2011-11-20 08:44:39

标签: c# thread-sleep

我正在尝试获取对象的构造函数以将字段初始化为某些内容,暂停30秒,然后将其设置为其他内容。

这是我的代码:

namespace Practice
{
    public enum TransactionStatus { Pending, Complete }

    public class Transaction
    {
        private TransactionStatus status;

        public Transaction()
        {
            this.status = TransactionStatus.Pending;
            //(I'm trying to set this to TransactionStatus.Complete after 30 seconds. What do I do afterwards?)
        }

        // Here is the method to do it... Am I right to think that.status this must be reset this.status in the constructor?
        public TransactionStatus SetStatus()
        {
            // sleep for 30 seconds and then proceed.
            System.Threading.Thread.Sleep(3000);
            return TransactionStatus.Complete;
        }
    }

2 个答案:

答案 0 :(得分:4)

说实话,我不会把它放在构造函数中。我会在主代码中做到这一点:

TransactionStatus status = new TransactionStatus();

Thread.Sleep(3000);

status.SetStatus();

当然会阻止整个程序。如果你不想这样,你将不得不编写自己的函数并将其称为单独的线程。再次在主要代码中。

那说我真的可以理解你为什么要做这样的事情。

答案 1 :(得分:3)

这是另一种欺骗方法,因为你说你正在使用toString();

private DateTime called;

public TranlationStatus()
{
    this.called = DateTime.Now; 
}

public ToString()
{
    if (this.called - DateTime.Now < new TimeSpan(0,0,20))
    {
        return TransationStatus.Pending.ToString();
    }
    else
    {
        return TransactionStatus.Complete.ToString();
    }
}