TimeConstraint2.cs 966 B

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