C# Wait until condition is true

后端 未结 7 1601
暖寄归人
暖寄归人 2020-12-24 05:52

I am trying to write a code that executes when a condition is met. Currently, I am using while...loop, which I know is not very efficient. I am also looking at AutoResetEven

7条回答
  •  春和景丽
    2020-12-24 06:22

    Ended up writing this today and seems to be ok. Your usage could be:

    await TaskEx.WaitUntil(isExcelInteractive);

    code (including the inverse operation)

    public static class TaskEx
    {
        /// 
        /// Blocks while condition is true or timeout occurs.
        /// 
        /// The condition that will perpetuate the block.
        /// The frequency at which the condition will be check, in milliseconds.
        /// Timeout in milliseconds.
        /// 
        /// 
        public static async Task WaitWhile(Func condition, int frequency = 25, int timeout = -1)
        {
            var waitTask = Task.Run(async () =>
            {
                while (condition()) await Task.Delay(frequency);
            });
    
            if(waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
                throw new TimeoutException();
        }
    
        /// 
        /// Blocks until condition is true or timeout occurs.
        /// 
        /// The break condition.
        /// The frequency at which the condition will be checked.
        /// The timeout in milliseconds.
        /// 
        public static async Task WaitUntil(Func condition, int frequency = 25, int timeout = -1)
        {
            var waitTask = Task.Run(async () =>
            {
                while (!condition()) await Task.Delay(frequency);
            });
    
            if (waitTask != await Task.WhenAny(waitTask, 
                    Task.Delay(timeout))) 
                throw new TimeoutException();
        }
    }
    

    Example usage: https://dotnetfiddle.net/Vy8GbV

提交回复
热议问题