TimeConstraint.cs 943 B

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