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

前端 未结 4 630
误落风尘
误落风尘 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:24

    I've made a work-around starting from @Roger's answer. (A friend of mine has given good advices regarding this too)... I copy it here I guess it could be useful:

    /// 
    /// Recurrent Cancellable Task
    /// 
    public static class RecurrentCancellableTask
    {
        /// 
        /// Starts a new task in a recurrent manner repeating it according to the polling interval.
        /// Whoever use this method should protect himself by surrounding critical code in the task 
        /// in a Try-Catch block.
        /// 
        /// The action.
        /// The poll interval.
        /// The token.
        /// The task creation options
        public static void StartNew(Action action, 
            TimeSpan pollInterval, 
            CancellationToken token, 
            TaskCreationOptions taskCreationOptions = TaskCreationOptions.None)
        {
            Task.Factory.StartNew(
                () =>
                {
                    do
                    {
                        try
                        {
                            action();
                            if (token.WaitHandle.WaitOne(pollInterval)) break;
                        }
                        catch
                        {
                            return;
                        }
                    }
                    while (true);
                },
                token,
                taskCreationOptions,
                TaskScheduler.Default);
        }
    }
    

提交回复
热议问题