using System;
using System.Threading.Tasks;
namespace InABox.Core
{
public static class TaskUtils
{
///
/// 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();
}
}
}