TimeConstraint.cs 896 B

123456789101112131415161718192021222324252627282930313233
  1. using Jint.Runtime;
  2. using System.Threading;
  3. namespace Jint.Constraints;
  4. internal sealed class TimeConstraint : Constraint
  5. {
  6. private readonly TimeSpan _timeout;
  7. private CancellationTokenSource? _cts;
  8. internal TimeConstraint(TimeSpan timeout)
  9. {
  10. _timeout = timeout;
  11. }
  12. public override void Check()
  13. {
  14. if (_cts?.IsCancellationRequested == true)
  15. {
  16. ExceptionHelper.ThrowTimeoutException();
  17. }
  18. }
  19. public override void Reset()
  20. {
  21. _cts?.Dispose();
  22. // This cancellation token source is very likely not disposed property, but it only allocates a timer, so not a big deal.
  23. // But using the cancellation token source is faster because we do not have to check the current time for each statement,
  24. // which means less system calls.
  25. _cts = new CancellationTokenSource(_timeout);
  26. }
  27. }