Пример #1
0
        private void CyclicTask()
        {
            while (true)
            {
                try
                {
                    if (!isRunning)
                    {
                        Task.Delay(1000).Wait();
                        continue;
                    }

                    if (!(runningTaskInfo == null || runningTaskInfo.Task.IsCompleted || runningTaskInfo.Task.IsFaulted || runningTaskInfo.Task.IsCanceled))
                    {
                        Task.Delay(10).Wait();
                        continue;
                    }

                    if (!tasks.Any(x => x != null && x.Status == TaskStatus.Waiting))
                    {
                        Task.Delay(10).Wait();
                        continue;
                    }
                    if (runningTaskInfo != null)
                    {
                        runningTaskInfo.Status = TaskStatus.Completed;
                    }

                    var waittingTask = tasks.FirstOrDefault(x => x.Status == TaskStatus.Waiting);
                    waittingTask.Status = TaskStatus.Running;

                    this.runningTaskInfo = waittingTask;
                    waittingTask.Task.Start();

                    Task.WaitAll(waittingTask.Task);
                    tasks.RemoveAll(x => x == null || x.Status == TaskStatus.Canceded || x.Status == TaskStatus.Completed || runningTaskInfo.Task.IsFaulted || x.Task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.ToString());
                    tasks.RemoveAll(x => x == null || x.Status == TaskStatus.Canceded || x.Status == TaskStatus.Completed || runningTaskInfo.Task.IsFaulted || x.Task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion);
                }
            }
        }