TaskExtensions.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #if ENABLE_MONO && (DEVELOPMENT_BUILD || UNITY_EDITOR)
  2. using System;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using UnityEngine;
  6. namespace SingularityGroup.HotReload {
  7. internal static class TaskExtensions {
  8. public static async void Forget(this Task task, CancellationToken token = new CancellationToken()) {
  9. try {
  10. await task;
  11. if(task.IsFaulted) {
  12. throw task.Exception ?? new Exception("unknown exception " + task);
  13. }
  14. token.ThrowIfCancellationRequested();
  15. }
  16. catch(OperationCanceledException) {
  17. // ignore
  18. } catch(Exception ex) {
  19. if(!token.IsCancellationRequested) {
  20. Log.Exception(ex);
  21. }
  22. }
  23. }
  24. /// <summary>
  25. /// Blocks until condition is true or timeout occurs.
  26. /// </summary>
  27. /// <param name="condition">The break condition.</param>
  28. /// <param name="pollInterval">The frequency at which the condition will be checked.</param>
  29. /// <param name="timeoutMs">The timeout in milliseconds.</param>
  30. /// <returns>True on condition became true, False if timeouted</returns>
  31. // credit: https://stackoverflow.com/a/52357854/5921285
  32. public static async Task<bool> WaitUntil(Func<bool> condition, int timeoutMs = -1, int pollInterval = 33) {
  33. var waitTask = Task.Run(async () => {
  34. while (!condition()) await Task.Delay(pollInterval);
  35. });
  36. if (waitTask != await Task.WhenAny(waitTask,
  37. Task.Delay(timeoutMs))) {
  38. // timed out
  39. return false;
  40. }
  41. return true;
  42. }
  43. }
  44. }
  45. #endif