是否有最佳方法来实现线程之间的延迟?

时间:2020-09-25 09:15:55

标签: c# timer cron thread-safety thread-sleep

用例非常简单

我有这个用于启动线程

主班

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

线程类

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

}

想法是线程执行大约需要花费时间。 6秒 我想要6个线程,它们以1秒的间隔开始

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

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

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

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

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

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

我看到了很多有关使用计时器或cronjobs的想法,但我不知道如何以正确的方式实现它们

1 个答案:

答案 0 :(得分:3)

.Net中解决此问题的另一种“规范”方法是使用任务并行库,而不是手动控制线程。下面的控制台程序说明了如何在后台线程上运行6个线程,它们之间有一秒钟的延迟。

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");
    }
}

使用任务并行库进行异步编程已很好地解释了in the documentation

相关问题