Created
November 5, 2025 16:15
-
-
Save wellingtonjhn/c5b91c0729f688541a9fbeb2bb2cbfd1 to your computer and use it in GitHub Desktop.
Wait until some action is done or until timeout is reached.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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