PublicInterfaceTests.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Collections.Concurrent;
  2. using Jint.Native;
  3. using Jint.Native.Function;
  4. namespace Jint.Tests.PublicInterface
  5. {
  6. public class PublicInterfaceTests
  7. {
  8. [Fact]
  9. public void BindFunctionInstancesArePublic()
  10. {
  11. var engine = new Engine(options =>
  12. {
  13. options.AllowClr();
  14. });
  15. using var emulator = new SetTimeoutEmulator(engine);
  16. engine.SetValue("emulator", emulator);
  17. engine.Execute(@"
  18. var coolingObject = {
  19. coolDownTime: 1000,
  20. cooledDown: false
  21. }
  22. emulator.SetTimeout(function() {
  23. coolingObject.cooledDown = true;
  24. }.bind(coolingObject), coolingObject.coolDownTime);
  25. ");
  26. }
  27. private class SetTimeoutEmulator : IDisposable
  28. {
  29. private readonly Engine _engine;
  30. private readonly ConcurrentQueue<JsValue> _queue = new();
  31. private readonly Task _queueProcessor;
  32. private readonly CancellationTokenSource _quit = new();
  33. private bool _disposedValue;
  34. public SetTimeoutEmulator(Engine engine)
  35. {
  36. _engine = engine ?? throw new ArgumentNullException(nameof(engine));
  37. _queueProcessor = Task.Run(() =>
  38. {
  39. while (!_quit.IsCancellationRequested)
  40. {
  41. while (_queue.TryDequeue(out var queueEntry))
  42. {
  43. if (queueEntry is FunctionInstance fi)
  44. {
  45. _engine.Invoke(fi);
  46. }
  47. else if (queueEntry is BindFunctionInstance bfi)
  48. {
  49. _engine.Invoke(bfi);
  50. }
  51. else
  52. {
  53. _engine.Execute(queueEntry.ToString());
  54. }
  55. }
  56. }
  57. });
  58. }
  59. public void SetTimeout(JsValue script, object timeout)
  60. {
  61. _queue.Enqueue(script);
  62. }
  63. protected virtual void Dispose(bool disposing)
  64. {
  65. if (!_disposedValue)
  66. {
  67. if (disposing)
  68. {
  69. // TODO: dispose managed state (managed objects)
  70. _quit.Cancel();
  71. _queueProcessor.Wait();
  72. }
  73. _disposedValue = true;
  74. }
  75. }
  76. public void Dispose()
  77. {
  78. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  79. Dispose(disposing: true);
  80. GC.SuppressFinalize(this);
  81. }
  82. }
  83. }
  84. }