microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
source/npm/qsharp/src/cancellation.ts
48lines · 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 | readonly onCancellationRequested: (listener: (e: any) => any) => void; |
| 10 | } |
| 11 | |
| 12 | class InternalToken implements CancellationToken { |
| 13 | private eventTarget: EventTarget; |
| 14 | isCancellationRequested = false; |
| 15 | |
| 16 | constructor() { |
| 17 | this.eventTarget = new EventTarget(); |
| 18 | } |
| 19 | |
| 20 | onCancellationRequested(listener: (e: any) => any) { |
| 21 | this.eventTarget.addEventListener("cancelled", listener); |
| 22 | } |
| 23 | |
| 24 | cancel() { |
| 25 | if (this.isCancellationRequested) return; // Only fires once |
| 26 | |
| 27 | this.isCancellationRequested = true; |
| 28 | this.eventTarget.dispatchEvent(new Event("cancelled")); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | export class CancellationTokenSource { |
| 33 | private _token: InternalToken; |
| 34 | |
| 35 | constructor(parent?: CancellationToken) { |
| 36 | // There are some optimizations you can do here to lazily allocate, but keeping it simple for now. |
| 37 | this._token = new InternalToken(); |
| 38 | if (parent) parent.onCancellationRequested(() => this.cancel()); |
| 39 | } |
| 40 | |
| 41 | get token(): CancellationToken { |
| 42 | return this._token; |
| 43 | } |
| 44 | |
| 45 | cancel(): void { |
| 46 | this._token.cancel(); |
| 47 | } |
| 48 | } |
| 49 | |