How to create a thread/Task with a continuous loop?

前端 未结 4 635
误落风尘
误落风尘 2020-12-22 19:25

I am looking for the correct way/structure to create a loop in a Thread/Task...

The reason for this is, i need to check the DB every 15sec for report re

4条回答
  •  鱼传尺愫
    2020-12-22 20:18

    feeling adventurous?

    internal class Program
    {
        private static void Main(string[] args)
        {
            var ct = new CancellationTokenSource();
    
            new Task(() => Console.WriteLine("Running...")).Repeat(ct.Token, TimeSpan.FromSeconds(1));
    
            Console.WriteLine("Starting. Hit Enter to Stop.. ");
            Console.ReadLine();
    
            ct.Cancel();
    
            Console.WriteLine("Stopped. Hit Enter to exit.. ");
            Console.ReadLine();
        }
    }
    
    
    public static class TaskExtensions
    {
        public static void Repeat(this Task taskToRepeat, CancellationToken cancellationToken, TimeSpan intervalTimeSpan)
        {
            var action = taskToRepeat
                .GetType()
                .GetField("m_action", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(taskToRepeat) as Action;
    
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (cancellationToken.WaitHandle.WaitOne(intervalTimeSpan))
                        break;
                    if (cancellationToken.IsCancellationRequested)
                        break;
                    Task.Factory.StartNew(action, cancellationToken);
                }
            }, cancellationToken);
        }
    }
    

提交回复
热议问题