如何在C#中将我的线程(用户定义的线程)置于睡眠模式?

时间:2013-03-08 12:45:01

标签: c# asp.net multithreading c#-4.0

我在C#中创建了一个线程。现在我想将我创建的主题放入特定的时间。然后我想开始我的线程。我的目标是,我想每天晚上8点调用我的updateMark函数。在调用我的函数之后,该线程将在接下来的24小时内进入休眠状态。所以它将在第二天晚上8点再次开始,并定期进行相同的工作。

**My C# code:-**
    public class ThreadProcess
    {
        public static void Main()
        {

        }

        public void updateMark()
        {
             string temp=ok("hai");
        }

        public string ok(string temp)
        {
             return temp+"!!!!";
        }
    }

所以,我在另一个类中使用以下代码中的线程:

        string targetTime = "08:05:00 PM";
        string currentTime = DateTime.Now.ToString("HH:mm:ss tt");

        DateTime t11 = Convert.ToDateTime(targetTime, culture);
        DateTime t21 = Convert.ToDateTime(currentTime, culture);

        ThreadProcess tp = new ThreadProcess();
        Thread myThread = new Thread(tp.updateMark);
        myThread.Start();

        if (t11.TimeOfDay.Ticks > t21.TimeOfDay.Ticks)
        {
            TimeSpan duration = DateTime.Parse(targetTime, culture).Subtract(DateTime.Parse(currentTime, culture));
            int ms = (int)duration.TotalMilliseconds;

            //Thread.Sleep(ms);i want to put my thread into sleep
        }

        while (true)
        {               
            myThread.start();

            Thread.Sleep(86400000);//put thread in sleep mode for next 24 hours...86400000 milleseconds...
        }      

请指导我摆脱这个问题...

2 个答案:

答案 0 :(得分:2)

创建一个包含存储过程的对象是不是更合乎逻辑。然后在某个时间,每晚调用该对象内的run方法。不需要随机睡眠线程,内存将在完成后自行清理。

的伪代码

TargetTime := 8:00PM.
// Store the target time.
Start Timer.
// Start the timer, so it will tick every second or something. That's up to you.
function tick()
{
    CurrentTime := current time.
    // Grab the current time.
    if(CurrentTime == TargetTime)
    {
         // If CurrentTime and TargetTime match, we run the code.
         // Run respective method.
    }
}

答案 1 :(得分:1)

我认为你应该使用计时器代替Thread.Sleep

.NET中有不同类型的计时器,您可以阅读其中一些here

我建议基于System.Threading.Timer的以下简化实现:

public class ScheduledJob
{
    //Period of time the timer will be raised. 
    //Not too often to prevent the system overload.
    private readonly TimeSpan _period = TimeSpan.FromMinutes(1);
    //08:05:00 PM
    private readonly TimeSpan _targetDayTime = new TimeSpan(20, 5, 0);
    private readonly Action _action;
    private readonly Timer _timer;

    private DateTime _prevTime;

    public ScheduledJob(Action action)
    {
        _action = action;
        _timer = new Timer(TimerRaised, null, 0, _period.Milliseconds);
    }

    private void TimerRaised(object state)
    {
        var currentTime = DateTime.Now;

        if (_prevTime.TimeOfDay < _targetDayTime
            && currentTime.TimeOfDay >= _targetDayTime)
        {
            _action();
        }

        _prevTime = currentTime;
    }
}

然后,在您的客户端代码中,只需调用:

var job = new ScheduledJob(() =>
    {
        //Code to implement on timer raised. Run your thread here.
    });