1

我在 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...
        }      

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

4

2 回答 2

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.
    }
}
于 2013-03-08T12:46:58.100 回答
1

我认为您应该使用计时器而不是Thread.Sleep在您的情况下。

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

我建议基于以下简化实现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.
    });
于 2013-03-08T13:54:28.230 回答