Is it a good idea to use longtime Thread.Sleep?

c#, multithreading

Solution

Both approaches are in most cases incorrect. Usual solution for this kind of problems is using System.Threading.Timer. Sample code for your case can look like that:

private void CheckJobs(object state)
{
    lock (Locker)
    {
        // checks job list.
        var jobs = foo.GetIncomingTimeJobs();
        foreach (var job in jobs)
        {
            var thread = new Thread(foo);
            thread.Start();
        }
    }
}

private void StartProcessing()
{
    var timer = new System.Threading.Timer(CheckJobs, null, 0, 10000);
}

When you call StartProcessing() function, the timer will be initialized and jobs list will be checked every 10 seconds.

If you go with Thread.Sleep() your application will become very unresponsive.

Problem

I have a job list. Each job has its own run time. They need to run when it comes time. I think two different ways. ``` public class Job { public int JobPeriod {get;set;} // for example as hour: daily = 24, weekly = 7 * 24, monthly = 30 * 24 public DateTime RunTime {get;set} } ``` First Way : I start a new main thread. This thread checks jobs at certain time interval (5 sec, 10 sec etc.). When a job's run time has come, the main thread will start and finish the job. The main thread which continually run in this way. ``` while (true) { lock (Locker) { // checks job list. var jobs = foo.GetIncomingTimeJobs(); foreach (var job in jobs) { ParameterizedThreadStart ts = RunJob; var th = new Thread(ts); th.Start(job); } Thread.Sleep(10000); } } public void RunJob(Job job) { // do somethings } ``` Second Way : When application is started, I create a new thread for each job in the job list. All of these created threads will start. When Job's thread is started, job's thread checks the job's run time. For example : ``` var jobs = foo.GetAllJobs(); foreach (var job in jobs) { ParameterizedThreadStart ts = RunJob; var th = new Thread(ts); th.Start(job); } public void RunJob(Job job) { while (true) { lock (Locker) { // do somethings var period = job.JobPeriod * 60 * 1000; Thread.Sleep(period); } } } ``` If there are ten jobs , there will be ten threads. And These ten threads will never end. will sleep, will continue, will sleep, will continue ... Is it normal for threads to sleep such a long time ? Which way should I use ? Or Is there another way of doing such a thing?

Original source