1 | ;
|
2 | /*! *****************************************************************************
|
3 | Copyright (c) Microsoft Corporation.
|
4 | Licensed under the Apache License, Version 2.0.
|
5 |
|
6 | See LICENSE file in the project root for details.
|
7 | ***************************************************************************** */
|
8 | Object.defineProperty(exports, "__esModule", { value: true });
|
9 | const list_1 = require("./list");
|
10 | const cancellation_1 = require("./cancellation");
|
11 | const utils_1 = require("./utils");
|
12 | const adapter_1 = require("./adapter");
|
13 | /**
|
14 | * Asynchronously notifies one or more waiting Promises that an event has occurred.
|
15 | */
|
16 | class AutoResetEvent {
|
17 | /**
|
18 | * Initializes a new instance of the AutoResetEvent class.
|
19 | *
|
20 | * @param initialState A value indicating whether to set the initial state to signaled.
|
21 | */
|
22 | constructor(initialState) {
|
23 | this._waiters = new list_1.LinkedList();
|
24 | if (utils_1.isMissing(initialState))
|
25 | initialState = false;
|
26 | if (!utils_1.isBoolean(initialState))
|
27 | throw new TypeError("Boolean expected: initialState.");
|
28 | this._signaled = initialState;
|
29 | }
|
30 | /**
|
31 | * Sets the state of the event to signaled, resolving one or more waiting Promises.
|
32 | * The event is then automatically reset.
|
33 | */
|
34 | set() {
|
35 | if (!this._signaled) {
|
36 | this._signaled = true;
|
37 | if (this._waiters.size > 0) {
|
38 | for (const waiter of this._waiters.drain()) {
|
39 | if (waiter)
|
40 | waiter();
|
41 | }
|
42 | this._signaled = false;
|
43 | }
|
44 | }
|
45 | }
|
46 | /**
|
47 | * Sets the state of the event to nonsignaled, causing asynchronous operations to pause.
|
48 | */
|
49 | reset() {
|
50 | this._signaled = false;
|
51 | }
|
52 | /**
|
53 | * Asynchronously waits for the event to become signaled.
|
54 | *
|
55 | * @param token A CancellationToken used to cancel the request.
|
56 | */
|
57 | wait(token) {
|
58 | return new Promise((resolve, reject) => {
|
59 | const _token = adapter_1.getToken(token);
|
60 | _token.throwIfCancellationRequested();
|
61 | if (this._signaled) {
|
62 | resolve();
|
63 | this._signaled = false;
|
64 | return;
|
65 | }
|
66 | const node = this._waiters.push(() => {
|
67 | registration.unregister();
|
68 | resolve();
|
69 | });
|
70 | const registration = _token.register(() => {
|
71 | node.list.deleteNode(node);
|
72 | reject(new cancellation_1.CancelError());
|
73 | });
|
74 | });
|
75 | }
|
76 | }
|
77 | exports.AutoResetEvent = AutoResetEvent;
|