workerManager.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. import { LanguageServiceDefaults } from './monaco.contribution';
  6. import type { CSSWorker } from './cssWorker';
  7. import { editor, IDisposable, Uri } from './fillers/monaco-editor-core';
  8. const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min
  9. export class WorkerManager {
  10. private _defaults: LanguageServiceDefaults;
  11. private _idleCheckInterval: number;
  12. private _lastUsedTime: number;
  13. private _configChangeListener: IDisposable;
  14. private _worker: editor.MonacoWebWorker<CSSWorker>;
  15. private _client: Promise<CSSWorker>;
  16. constructor(defaults: LanguageServiceDefaults) {
  17. this._defaults = defaults;
  18. this._worker = null;
  19. this._idleCheckInterval = window.setInterval(() => this._checkIfIdle(), 30 * 1000);
  20. this._lastUsedTime = 0;
  21. this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker());
  22. }
  23. private _stopWorker(): void {
  24. if (this._worker) {
  25. this._worker.dispose();
  26. this._worker = null;
  27. }
  28. this._client = null;
  29. }
  30. dispose(): void {
  31. clearInterval(this._idleCheckInterval);
  32. this._configChangeListener.dispose();
  33. this._stopWorker();
  34. }
  35. private _checkIfIdle(): void {
  36. if (!this._worker) {
  37. return;
  38. }
  39. let timePassedSinceLastUsed = Date.now() - this._lastUsedTime;
  40. if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) {
  41. this._stopWorker();
  42. }
  43. }
  44. private _getClient(): Promise<CSSWorker> {
  45. this._lastUsedTime = Date.now();
  46. if (!this._client) {
  47. this._worker = editor.createWebWorker<CSSWorker>({
  48. // module that exports the create() method and returns a `CSSWorker` instance
  49. moduleId: 'vs/language/css/cssWorker',
  50. label: this._defaults.languageId,
  51. // passed in to the create() method
  52. createData: {
  53. options: this._defaults.options,
  54. languageId: this._defaults.languageId
  55. }
  56. });
  57. this._client = <Promise<CSSWorker>>(<any>this._worker.getProxy());
  58. }
  59. return this._client;
  60. }
  61. getLanguageServiceWorker(...resources: Uri[]): Promise<CSSWorker> {
  62. let _client: CSSWorker;
  63. return this._getClient()
  64. .then((client) => {
  65. _client = client;
  66. })
  67. .then((_) => {
  68. return this._worker.withSyncedResources(resources);
  69. })
  70. .then((_) => _client);
  71. }
  72. }