Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/test/taskRunner.ts
13383 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
class CTask<T> {
6
7
private resolve!: (value: T) => void;
8
private reject!: (err: any) => void;
9
public result: Promise<T>;
10
11
constructor(private readonly _execute: () => Promise<T>) {
12
this.result = new Promise<T>((resolve, reject) => {
13
this.resolve = resolve;
14
this.reject = reject;
15
});
16
}
17
18
async execute(): Promise<void> {
19
try {
20
const result = await this._execute();
21
this.resolve(result);
22
} catch (err) {
23
this.reject(err);
24
}
25
}
26
}
27
28
export class TaskRunner {
29
private readonly tasks: CTask<any>[] = [];
30
private pendingTasks = 0;
31
32
private waitResolve: (() => void) | undefined;
33
// private waitPromise: Promise<void> | undefined;
34
constructor(
35
public readonly parallelism: number
36
) { }
37
38
run<T>(task: CTask<T> | (() => Promise<T>)): Promise<T> {
39
if (!(task instanceof CTask)) {
40
task = new CTask(task);
41
}
42
this.tasks.push(task);
43
this.launchTaskIfPossible();
44
return task.result;
45
}
46
47
private launchTaskIfPossible(): void {
48
if (this.tasks.length === 0) {
49
// all tasks completed
50
return;
51
}
52
if (this.pendingTasks >= this.parallelism) {
53
// too many tasks running
54
return;
55
}
56
const task = this.tasks.shift()!;
57
this.pendingTasks++;
58
task.execute().then(() => this.onDidCompleteTask(), () => this.onDidCompleteTask());
59
}
60
61
private onDidCompleteTask(): void {
62
this.pendingTasks--;
63
this.launchTaskIfPossible();
64
65
if (this.pendingTasks === 0) {
66
// all tasks completed
67
// this.waitPromise = undefined;
68
this.waitResolve?.();
69
}
70
}
71
72
async waitForCompletion(): Promise<void> {
73
throw new Error('not implemented');
74
// if (!this.waitPromise) {
75
// this.waitPromise = new Promise<void>(resolve => this.waitResolve = resolve);
76
// }
77
// // for (let i = 0; i < this.parallelism; i++) {
78
// // this.launchTaskIfPossible();
79
// // }
80
// return this.waitPromise;
81
}
82
}
83
84