microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
npm/src/cancellation.ts
50lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | export interface CancellationToken { |
| 5 | // A flag signalling if cancellation has been requested. |
| 6 | readonly isCancellationRequested: boolean; |
| 7 | |
| 8 | // An event which fires when cancellation is requested. |
| 9 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 10 | readonly onCancellationRequested: (listener: (e: any) => any) => void; |
| 11 | } |
| 12 | |
| 13 | class InternalToken implements CancellationToken { |
| 14 | private eventTarget: EventTarget; |
| 15 | isCancellationRequested = false; |
| 16 | |
| 17 | constructor() { |
| 18 | this.eventTarget = new EventTarget(); |
| 19 | } |
| 20 | |
| 21 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 22 | onCancellationRequested(listener: (e: any) => any) { |
| 23 | this.eventTarget.addEventListener("cancelled", listener); |
| 24 | } |
| 25 | |
| 26 | cancel() { |
| 27 | if (this.isCancellationRequested) return; // Only fires once |
| 28 | |
| 29 | this.isCancellationRequested = true; |
| 30 | this.eventTarget.dispatchEvent(new Event("cancelled")); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | export class CancellationTokenSource { |
| 35 | private _token: InternalToken; |
| 36 | |
| 37 | constructor(parent?: CancellationToken) { |
| 38 | // There are some optimizations you can do here to lazily allocate, but keeping it simple for now. |
| 39 | this._token = new InternalToken(); |
| 40 | if (parent) parent.onCancellationRequested(() => this.cancel()); |
| 41 | } |
| 42 | |
| 43 | get token(): CancellationToken { |
| 44 | return this._token; |
| 45 | } |
| 46 | |
| 47 | cancel(): void { |
| 48 | this._token.cancel(); |
| 49 | } |
| 50 | } |
| 51 | |