TimeConstraint2.cs 980 B

1234567891011121314151617181920212223242526272829303132333435
  1. using Jint.Runtime;
  2. using System;
  3. using System.Threading;
  4. namespace Jint.Constraints
  5. {
  6. internal sealed class TimeConstraint2 : IConstraint
  7. {
  8. private readonly TimeSpan _timeout;
  9. private CancellationTokenSource cts;
  10. public TimeConstraint2(TimeSpan timeout)
  11. {
  12. _timeout = timeout;
  13. }
  14. public void Check()
  15. {
  16. if (cts.IsCancellationRequested)
  17. {
  18. ExceptionHelper.ThrowTimeoutException();
  19. }
  20. }
  21. public 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. }
  30. }