| | 1 | | // Copyright (c) 2020-2024 dotBunny Inc. |
| | 2 | | // dotBunny licenses this file to you under the BSL-1.0 license. |
| | 3 | | // See the LICENSE file in the project root for more information. |
| | 4 | |
|
| | 5 | | using System; |
| | 6 | | using System.Collections; |
| | 7 | | using System.Threading.Tasks; |
| | 8 | |
|
| | 9 | | namespace GDX.Threading |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Some useful wait while methods to control program flow. |
| | 13 | | /// </summary> |
| | 14 | | public static class WaitWhile |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Wait using an <see cref="IEnumerator" /> while the <paramref name="conditional" /> is true. |
| | 18 | | /// </summary> |
| | 19 | | /// <param name="conditional">A function evaluated to determine if the wait continues.</param> |
| | 20 | | /// <returns>Yields null values.</returns> |
| | 21 | | public static IEnumerator GetEnumerator(Func<bool> conditional) |
| 1 | 22 | | { |
| 2 | 23 | | while (conditional()) |
| 1 | 24 | | { |
| 1 | 25 | | yield return null; |
| 1 | 26 | | } |
| 1 | 27 | | } |
| | 28 | |
|
| | 29 | | /// <summary> |
| | 30 | | /// Wait asynchronously while the <paramref name="conditional" /> is true. |
| | 31 | | /// </summary> |
| | 32 | | /// <param name="conditional">A function evaluated to determine if the wait continues.</param> |
| | 33 | | public static async Task GetTask(Func<bool> conditional) |
| 1 | 34 | | { |
| 3 | 35 | | await Task.Run(() => |
| 1 | 36 | | { |
| 19 | 37 | | while (conditional()) |
| 18 | 38 | | { |
| 18 | 39 | | Task.Delay(1).Wait(); |
| 18 | 40 | | } |
| 1 | 41 | | }); |
| 1 | 42 | | } |
| | 43 | | } |
| | 44 | | } |