How to terminate a worker thread correctly in c#

后端 未结 4 1654
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 23:36

Problem statement

I have a worker thread that basically scans a folder, going into the files within it, and then sleeps for a while. The scanning operat

4条回答
  •  野性不改
    2021-02-16 00:14

    I came up with separately scheduling the task:

    using System;
    using System.Threading;
    
    namespace ProjectEuler
    {
        class Program
        {
            //const double cycleIntervalMilliseconds = 10 * 60 * 1000;
            const double cycleIntervalMilliseconds = 5 * 1000;
            static readonly System.Timers.Timer scanTimer =
                new System.Timers.Timer(cycleIntervalMilliseconds);
            static bool scanningEnabled = true;
            static readonly ManualResetEvent scanFinished =
                new ManualResetEvent(true);
    
            static void Main(string[] args)
            {
                scanTimer.Elapsed +=
                    new System.Timers.ElapsedEventHandler(scanTimer_Elapsed);
                scanTimer.Enabled = true;
    
                Console.ReadLine();
                scanningEnabled = false;
                scanFinished.WaitOne();
            }
    
            static void  scanTimer_Elapsed(object sender,
                System.Timers.ElapsedEventArgs e)
            {
                scanFinished.Reset();
                scanTimer.Enabled = false;
    
                if (scanningEnabled)
                {
                    try
                    {
                        Console.WriteLine("Processing");
                        Thread.Sleep(5000);
                        Console.WriteLine("Finished");
                    }
                    finally
                    {
                        scanTimer.Enabled = scanningEnabled;
                        scanFinished.Set();
                    }
                }
            }
        }
    }
    

提交回复
热议问题