Is “while (true)” usually used for a permanent thread?

后端 未结 6 1213
温柔的废话
温柔的废话 2021-02-04 07:18

I\'m relatively new to coding; most of my \"work\" has been just simple GUI apps that only function for one thing, so I haven\'t had to thread much.

Anyway, one thing I\

6条回答
  •  自闭症患者
    2021-02-04 08:00

    Additionally You can use System.Threading.Timer. In this case, we don't have to use the Sleep method. Simple example:

    public sealed class TimerTask
    {
        private Timer _timer;
        private int _period;
    
        public TimerTask(int period)
        {
            _period = period;
            _timer = new Timer(new TimerCallback(Run), "Hello ....", Timeout.Infinite, period);
        }
    
        public void Start()
        {
            _timer.Change(0, _period);
        }
    
        public void Stop()
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
        }
    
        private void Run(Object param)
        {
            Console.WriteLine(param.ToString());
        }
    }
    

    Use:

    public static class Program
    {
        [STAThread]
        static void Main(String[] args)
        {
            TimerTask task = new TimerTask(1000);
            Console.WriteLine("Timer start.");
            task.Start();
            Console.ReadLine();
            Console.WriteLine("Timer stop.");
            task.Stop();
            Console.ReadLine();
            Console.WriteLine("Timer start.");
            task.Start();
            Console.ReadLine();
            Console.WriteLine("Timer stop.");
            task.Stop();
            Console.ReadLine();
        }
    }
    

    Console output:

    Timer start.
    Hello ....
    Hello ....
    Hello ....
    
    Timer stop.
    
    Timer start.
    Hello ....
    Hello ....
    
    Timer stop.
    

提交回复
热议问题