Alternatives to Thread.Sleep()

后端 未结 11 1286
清歌不尽
清歌不尽 2020-11-27 03:48

Every N minutes we want to run through a list of tasks. So we\'ve created a task executor with a

do { DoWork(); }while(!stopRequested)

No

11条回答
  •  旧时难觅i
    2020-11-27 04:15

    If all your thread is doing is something like:

    while (!stop_working)
    {
        DoWork();
        Thread.Sleep(FiveMinutes);
    }
    

    Then I would suggest not using a thread at all. First, there's no particularly good reason to incur the system overhead of a dedicated thread that spends most of its time sleeping. Secondly, if you set the stop_working flag 30 seconds after the thread stops sleeping, you'll have to wait four and a half minutes before the thread wakes up and terminates.

    I'd suggest as others have: use a timer:

    System.Threading.Timer WorkTimer;
    
    // Somewhere in your initialization:
    
    WorkTimer = new System.Threading.Timer((state) =>
        {
            DoWork();
        }, null, TimeSpan.FromMinutes(5.0), TimeSpan.FromMinutes(5.0));
    

    And to shut down:

     WorkTimer.Dispose();
    

提交回复
热议问题