Search code examples
c#timercronthread-safetythread-sleep

Is there a best method to implement a delay in between threads?


The usecase is pretty simple

I have this for starting the threads

Main class

 for (int x = 1; x <= numThreads; x++)
    {
        new ThreadComponent(x, this, creator).init();
    }

Thread class

public void init()
{
    thread = new Thread(doLogic);
    thread.IsBackground = true;
    thread.Start();
}
void doLogic()
{
    while (true)
    {
        
            doLogicGetData();
    }

}

Idea is that thread execution takes approx. 6 seconds I want 6 threads that start at 1 second interval

 1------1------

  2------2------

   3------3------ 

    4------4------

     5------5------

      6------6------ 

I saw a lot of ideas about using timers or cronjobs but i do not know how to implement them in a proper way


Solution

  • A more 'canonical' way to tackle this problem in .Net is using the Task Parallel Library instead of manually controlling threads. The console program below illustrates how you would run 6 threads on background threads, with a one second delay between them.

    class Program
    {
        public async static Task Main()
        {
            var cts = new CancellationTokenSource();
    
            List<Task> tasks = new List<Task>();
    
            for (int i = 0; i < 6; i++)
            {
                tasks.Add(Task.Run(() => DoWork(cts.Token), cts.Token));
                await Task.Delay(1000);
            }
    
            Console.WriteLine("Press ENTER to stop");
            Console.ReadLine();
            Console.WriteLine("Waiting for all threads to end");
            cts.Cancel();
            await Task.WhenAll(tasks);
        }
    
        public static void DoWork(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                Console.WriteLine($"Doing work on thread {Thread.CurrentThread.ManagedThreadId}");
                Thread.Sleep(10000); // simulating 10 seconds of CPU work;
            }
            Console.WriteLine($"Worker thread {Thread.CurrentThread.ManagedThreadId} cancelled");
        }
    }
    

    Asynchronous programming using the Task Parallel Library is explained pretty well in the documentation