using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 智慧物流软件系统
{
    /// <summary>
    /// 循环、暂停、继续、停止扩展
    /// </summary>
    public static class While
    {
        /// <summary>
        /// 带条件等待并检测停止、暂停
        /// </summary>
        /// <param name="func">不停的执行的任务，返回为true就跳出循环</param>
        public static async Task Wait(Func<bool> func, CancellationToken token = default, ManualResetEvent manualReset = default)
        {
            while (true)
            {
                token.ThrowIfCancellationRequested();
                manualReset?.WaitOne();
                token.ThrowIfCancellationRequested();

                if (func.Invoke())
                    break;

                await Task.Delay(200, token);
            }
        }

        /// <summary>
        /// 等待并检测停止、暂停
        /// </summary>
        public static void Wait(CancellationToken token = default, ManualResetEvent manualReset = default)
        {
            token.ThrowIfCancellationRequested();
            manualReset?.WaitOne();
            token.ThrowIfCancellationRequested();
        }
    }
}
