Skip to content

Instantly share code, notes, and snippets.

@wellingtonjhn
Created November 5, 2025 16:15
Show Gist options
  • Select an option

  • Save wellingtonjhn/c5b91c0729f688541a9fbeb2bb2cbfd1 to your computer and use it in GitHub Desktop.

Select an option

Save wellingtonjhn/c5b91c0729f688541a9fbeb2bb2cbfd1 to your computer and use it in GitHub Desktop.
Wait until some action is done or until timeout is reached.
public static class WaitUtils
{
/// <summary>
/// Wait until some action is done or until timeout is reached.
/// <code>
/// var waitResult = await WaitUtils.WaitUntilAsync(
/// async () =>
/// {
/// // some actions
/// var result = await db.FirstOrDefault(q=> q.Status == Status.Success);
/// return result;
/// },
/// timeout: TimeSpan.FromSeconds(50),
/// pollInterval: TimeSpan.FromSeconds(2)
/// );
/// </code>
/// </summary>
public static async Task<bool> WaitUntilAsync(
Func<Task<bool>> condition,
TimeSpan timeout,
TimeSpan? pollInterval = null
)
{
pollInterval ??= TimeSpan.FromMilliseconds(500);
var start = DateTime.UtcNow;
while (DateTime.UtcNow - start < timeout)
{
if (await condition())
{
return true;
}
await Task.Delay(pollInterval.Value);
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment