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

前端 未结 4 636
误落风尘
误落风尘 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条回答
  •  猫巷女王i
    2020-12-22 20:13

    Something like this would work:

    var cancellationTokenSource = new CancellationTokenSource();
    var task = Repeat.Interval(
            TimeSpan.FromSeconds(15),
            () => CheckDatabaseForNewReports(), cancellationTokenSource.Token);
    

    The Repeat class looks like this:

    internal static class Repeat
    {
        public static Task Interval(
            TimeSpan pollInterval,
            Action action,
            CancellationToken token)
        {
            // We don't use Observable.Interval:
            // If we block, the values start bunching up behind each other.
            return Task.Factory.StartNew(
                () =>
                {
                    for (;;)
                    {
                        if (token.WaitCancellationRequested(pollInterval))
                            break;
    
                        action();
                    }
                }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
    }
    
    static class CancellationTokenExtensions
    {
        public static bool WaitCancellationRequested(
            this CancellationToken token,
            TimeSpan timeout)
        {
            return token.WaitHandle.WaitOne(timeout);
        }
    }
    

提交回复
热议问题