diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index 0217f6d04cb40c4048170fc7e69a2a63c0231bc2..334d1f36db45e2ad9c5fc4aa15748bc05b579de8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -64,8 +64,14 @@ Enumerates the reasons for the last exit. You can use it together with [onCreate | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| -| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| -| NORMAL | 2 | The ability exits normally.| +| ABILITY_NOT_RESPONDING | 1 | The ability does not respond. This enum is supported since API version 9 and deprecated since API version 10. You are advised to use **APP_FREEZE**.| +| NORMAL | 2 | The ability exits normally because the user closes the application.| +| CPP_CRASH10+ | 3 | The ability exits due to abnormal signals on the local host.| +| JS_ERROR10+ | 4 | The ability exits due to a JS_ERROR fault triggered when an application has a JS syntax error that is not captured by developers.| +| APP_FREEZE10+ | 5 | The ability exits because watchdog detects that the application is frozen.| +| PERFORMANCE_CONTROL10+ | 6 | The ability exits due to system performance problems, for example, insufficient device memory.| +| RESOURCE_CONTROL10+ | 7 | The ability exits because the system resource usage (CPU, I/O, or memory usage) exceeds the upper limit.| +| UPGRADE10+ | 8 | The ability exits due to an update.| **Example** @@ -218,3 +224,24 @@ class MyAbility extends UIAbility { } } ``` + +## AbilityConstant.ContinueState10+ + +Enumerates the mission continuation states of the application. It is used in the [setMissionContinueState](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) API of [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------- | --------- | ------------------------------------------------------------ | +| ACTIVE | 0 | Mission continuation is activated for the current application. | +| INACTIVE | 1 | Mission continuation is not activated for the current application. | + +**Example** + +```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); +``` diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index f6a93974ae9bd73a144b93b42213720ebdad228f..0b869f14bb861a49f54cd2a7ef79976bedb7a84b 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -20,6 +20,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles.| | ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle. | |ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | Permission to enable or disable an application or ability. | +| ohos.permission.GET_INSTALLED_BUNDLE_LIST | system_basic | Permission to read installed application list.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -115,7 +116,7 @@ Enumerates the types of Extension abilities. | PRINT10+ | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.| | PUSH10+ | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved.| | DRIVER10+ | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.| -| APP_ACCOUNT_AUTHORIZATION10+ | 19 | AuthorizationExtensionAbility: provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.| +| APP_ACCOUNT_AUTHORIZATION10+ | 19 | [AuthorizationExtensionAbility](js-apis-appAccount-authorizationExtensionAbility.md): provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.| @@ -677,7 +678,7 @@ Obtains the information about all bundles based on the given bundle flags and us **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -726,7 +727,7 @@ Obtains the information about all bundles based on the given bundle flags. This **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -765,7 +766,7 @@ Obtains the information about all bundles based on the given bundle flags and us **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -816,7 +817,7 @@ Obtains the information about all applications based on the given application fl **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -865,7 +866,7 @@ Obtains the information about all applications based on the given application fl **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -904,7 +905,7 @@ Obtains the information about all applications based on the given application fl **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -1752,7 +1753,7 @@ Enables or disables an ability. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the application.| | callback | AsyncCallback\ | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -1814,7 +1815,7 @@ Enables or disables an ability. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the application.| **Return value** @@ -3213,3 +3214,129 @@ try { hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); } ``` + +### bundleManager.getSpecifiedDistributionType10+ + +getSpecifiedDistributionType(bundleName: string): string; + +Obtains the distribution type of a bundle in synchronous mode. The return value is the **specifiedDistributionType** field value in [InstallParam](./js-apis-installer.md#installparam) passed when **install** is called. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| bundleName | string | Yes | Bundle name.| + +**Return value** + +| Type | Description | +| ------------- | -------------------------------------- | +| string | Distribution type of the bundle.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundleName is not found. | + +**Example** +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +let bundleName = "com.example.myapplication"; + +try { + let type = bundleManager.getSpecifiedDistributionType(bundleName); + console.info('getSpecifiedDistributionType successfully, type:' + type); +} catch (error) { + console.error('getSpecifiedDistributionType failed. Cause: ' + error.message); +} +``` + + +### bundleManager.getAdditionalInfo10+ + +getAdditionalInfo(bundleName: string): string; + +Obtains additional information about a bundle in synchronous mode. The return value is the **additionalInfo** field value in [InstallParam](./js-apis-installer.md#installparam) passed when **install** is called. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| bundleName | string | Yes | Bundle name.| + +**Return value** + +| Type | Description | +| ------------- | -------------------------------------- | +| string | Additional information about the bundle.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundleName is not found. | + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +let bundleName = "com.example.myapplication"; + +try { + let info = bundleManager.getAdditionalInfo(bundleName); + console.info('getAdditionalInfo successfully, additionInfo:' + info); +} catch (error) { + console.error('getAdditionalInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.getBundleInfoForSelfSync10+ + +getBundleInfoForSelfSync(bundleFlags: number): BundleInfo; + +Obtains the bundle information of this bundle based on the given bundle flags in synchronous mode. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | --------------------- | +| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | -------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.| + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; +try { + let data = bundleManager.getBundleInfoForSelfSync(bundleFlags); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelfSync successfully: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelfSync failed: %{public}s', err.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index 6de1a67d7af88229266bbdac7a4adb853479bb03..5e5fb1bbd6e67ef575778c601667f239b895e005 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -37,35 +37,32 @@ function printArgs(args) { console.log("printArgs: " + args); return args; } -async function taskpoolPriority() { - let task = new taskpool.Task(printArgs, 100); - - let highCount = 0; - let mediumCount = 0; - let lowCount = 0; - let allCount = 100; - for (let i = 0; i < allCount; i++) { - taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { - lowCount++; - console.log("taskpool lowCount is :" + lowCount); - }).catch((e) => { - console.error("low task error: " + e); - }) - taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { - mediumCount++; - console.log("taskpool mediumCount is :" + mediumCount); - }).catch((e) => { - console.error("medium task error: " + e); - }) - taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { - highCount++; - console.log("taskpool highCount is :" + highCount); - }).catch((e) => { - console.error("high task error: " + e); - }) - } + +let task = new taskpool.Task(printArgs, 100); // 100: test number +let highCount = 0; +let mediumCount = 0; +let lowCount = 0; +let allCount = 100; +for (let i = 0; i < allCount; i++) { + taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { + lowCount++; + console.log("taskpool lowCount is :" + lowCount); + }).catch((e) => { + console.error("low task error: " + e); + }) + taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { + mediumCount++; + console.log("taskpool mediumCount is :" + mediumCount); + }).catch((e) => { + console.error("medium task error: " + e); + }) + taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { + highCount++; + console.log("taskpool highCount is :" + highCount); + }).catch((e) => { + console.error("high task error: " + e); + }) } -taskpoolPriority(); ``` ## Task @@ -91,7 +88,7 @@ A constructor used to create a **Task** instance. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | +| ID| Error Message | | -------- | --------------------------------------- | | 10200014 | The function is not mark as concurrent. | @@ -107,6 +104,117 @@ function printArgs(args) { let task = new taskpool.Task(printArgs, "this is my first Task"); ``` +### isCanceled10+ + +static isCanceled(): boolean + +Checks whether the running task is canceled. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.| + +**Example** + +```ts +@Concurrent +function inspectStatus(arg) { + // do something + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled."); + // do something + return arg + 1; + } + // do something + return arg; +} +``` + +> **NOTE** +> +> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default. + +**Example** + +```ts +@Concurrent +function inspectStatus(arg) { + // Check the cancellation status and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // Wait for 2s. + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the cancellation status again and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; +} + +let task = new taskpool.Task(inspectStatus, 100); // 100: test number +taskpool.execute(task).then((res)=>{ + console.log("taskpool test result: " + res); +}).catch((err) => { + console.log("taskpool test occur error: " + err); +}); +// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101. +``` + +### setTransferList10+ + +setTransferList(transfer?: ArrayBuffer[]): void + +Sets the task transfer list. + +> **NOTE** +> +> This API is used to set the task transfer list in the form of **ArrayBuffer** in the task pool. The **ArrayBuffer** instance does not copy the content in the task to the worker thread during transfer. Instead, it transfers the buffer control right to the worker thread. After the transfer, the **ArrayBuffer** instance becomes invalid. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------------------------------------- | +| transfer | ArrayBuffer[] | No | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.| + +**Example** + +```ts +let buffer = new ArrayBuffer(8); +let view = new Uint8Array(buffer); +let buffer1 = new ArrayBuffer(16); +let view1 = new Uint8Array(buffer1); + +console.info("testTransfer view byteLength: " + view.byteLength); +console.info("testTransfer view1 byteLength: " + view1.byteLength); +@Concurrent +function testTransfer(arg1, arg2) { + console.info("testTransfer arg1 byteLength: " + arg1.byteLength); + console.info("testTransfer arg2 byteLength: " + arg2.byteLength); + return 100; +} +let task = new taskpool.Task(testTransfer, view, view1); +task.setTransferList([view.buffer, view1.buffer]); +taskpool.execute(task).then((res)=>{ + console.info("test result: " + res); +}).catch((e)=>{ + console.error("test catch: " + e); +}) +console.info("testTransfer view byteLength: " + view.byteLength); +console.info("testTransfer view1 byteLength: " + view1.byteLength); +``` + ### Attributes **System capability**: SystemCapability.Utils.Lang @@ -116,6 +224,96 @@ let task = new taskpool.Task(printArgs, "this is my first Task"); | function | Function | Yes | Yes | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | | arguments | unknown[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +## TaskGroup10+ + +Implements a task group. Before using any of the following APIs, you must create a **TaskGroup** instance. + +### constructor10+ + +constructor() + +Constructor used to create a **TaskGroup** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +let taskGroup = new taskpool.TaskGroup(); +``` + +### addTask10+ + +addTask(func: Function, ...args: unknown[]): void + +Adds the function to be executed to this task group. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; +} + +let taskGroup = new taskpool.TaskGroup(); +taskGroup.addTask(printArgs, 100); // 100: test number +``` + +### addTask10+ + +addTask(task: Task): void + +Adds a created task to this task group. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| task | [Task](#task) | Yes | Task to be added to the task group. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; +} + +let taskGroup = new taskpool.TaskGroup(); +let task = new taskpool.Task(printArgs, 200); // 200: test number +taskGroup.addTask(task); +``` + ## taskpool.execute execute(func: Function, ...args: unknown[]): Promise\ @@ -141,11 +339,11 @@ Places the function to be executed in the internal task queue of the task pool. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 10200003 | Worker initialization failure. | -| 10200006 | Serializing an uncaught exception failed. | -| 10200014 | The function is not mark as concurrent. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200003 | Worker initialization failure. | +| 10200006 | An exception occurred during serialization. | +| 10200014 | The function is not mark as concurrent. | **Example** @@ -156,12 +354,9 @@ function printArgs(args) { return args; } -async function taskpoolExecute() { - let value = await taskpool.execute(printArgs, 100); +taskpool.execute(printArgs, 100).then((value) => { // 100: test number console.log("taskpool result: " + value); -} - -taskpoolExecute(); +}); ``` ## taskpool.execute @@ -177,23 +372,23 @@ Places a task in the internal task queue of the task pool. The task will be dist | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------- | | task | [Task](#task) | Yes | Task to be executed. | -| priority | [Priority](#priority) | No | Priority of the task. The default value is **MEDIUM**.| +| priority | [Priority](#priority) | No | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.| **Return value** -| Type | Description | -| ---------------- | ------------------------------ | +| Type | Description | +| ---------------- | ---------------- | | Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 10200003 | Worker initialization failure. | -| 10200006 | Serializing an uncaught exception failed. | -| 10200014 | The function is not mark as concurrent. | +| ID| Error Message | +| -------- | ------------------------------------------- | +| 10200003 | Worker initialization failure. | +| 10200006 | An exception occurred during serialization. | +| 10200014 | The function is not mark as concurrent. | **Example** @@ -204,13 +399,72 @@ function printArgs(args) { return args; } -async function taskpoolExecute() { - let task = new taskpool.Task(printArgs, 100); - let value = await taskpool.execute(task); +let task = new taskpool.Task(printArgs, 100); // 100: test number +taskpool.execute(task).then((value) => { console.log("taskpool result: " + value); +}); +``` + +## taskpool.execute10+ + +execute(group: TaskGroup, priority?: Priority): Promise + +Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------- | ---- | -------------------------------------------------------------- | +| group | [TaskGroup](#taskgroup) | Yes | Task group to be executed. | +| priority | [Priority](#priority) | No | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 10200006 | An exception occurred during serialization. | + +**Example** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; } -taskpoolExecute(); +let taskGroup1 = new taskpool.TaskGroup(); +taskGroup1.addTask(printArgs, 10); // 10: test number +taskGroup1.addTask(printArgs, 20); // 20: test number +taskGroup1.addTask(printArgs, 30); // 30: test number + +let taskGroup2 = new taskpool.TaskGroup(); +let task1 = new taskpool.Task(printArgs, 100); // 100: test number +let task2 = new taskpool.Task(printArgs, 200); // 200: test number +let task3 = new taskpool.Task(printArgs, 300); // 300: test number +taskGroup2.addTask(task1); +taskGroup2.addTask(task2); +taskGroup2.addTask(task3); +taskpool.execute(taskGroup1).then((res) => { + console.info("taskpool execute res is:" + res); +}).catch((e) => { + console.error("taskpool execute error is:" + e); +}); +taskpool.execute(taskGroup2).then((res) => { + console.info("taskpool execute res is:" + res); +}).catch((e) => { + console.error("taskpool execute error is:" + e); +}); ``` ## taskpool.cancel @@ -231,91 +485,109 @@ Cancels a task in the task pool. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | -| -------- | ------------------------- | -| 10200015 | If the task is not exist. | -| 10200016 | If the task is running. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200015 | The task does not exist when it is canceled. | +| 10200016 | The task is executing when it is canceled. | -**Example of successful task cancellation** +Since API version 10, error code 10200016 is not reported when this API is called. + +**Example of canceling an ongoing task** ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; -} - -async function taskpoolCancel() { - let task = new taskpool.Task(printArgs, 100); - taskpool.execute(task); - try { - taskpool.cancel(task); - } catch (e) { - console.log("taskpool.cancel occur error:" + e); - } +function inspectStatus(arg) { + // Check the task cancellation state and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 2s sleep + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the task cancellation state again and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; } -taskpoolCancel(); +let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number +let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number +let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number +let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number +let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number +let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number +taskpool.execute(task1).then((res)=>{ + console.log("taskpool test result: " + res); +}).catch((err) => { + console.log("taskpool test occur error: " + err); +}); +let res2 = taskpool.execute(task2); +let res3 = taskpool.execute(task3); +let res4 = taskpool.execute(task4); +let res5 = taskpool.execute(task5); +let res6 = taskpool.execute(task6); +// Cancel the task 1s later. +setTimeout(()=>{ + taskpool.cancel(task1);}, 1000); ``` -**Example of a failure to cancel a task that has been executed** +## taskpool.cancel10+ -```ts -@Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; -} +cancel(group: TaskGroup): void -async function taskpoolCancel() { - let task = new taskpool.Task(printArgs, 100); - let value = taskpool.execute(task); - let start = new Date().getTime(); - while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. - continue; - } +Cancels a task group in the task pool. - try { - taskpool.cancel(task); // The task has been executed and fails to be canceled. - } catch (e) { - console.log("taskpool.cancel occur error:" + e); - } -} +**System capability**: SystemCapability.Utils.Lang -taskpoolCancel(); -``` +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------- | ---- | -------------------- | +| group | [TaskGroup](#taskgroup) | Yes | Task group to cancel.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -**Example of a failure to cancel an ongoing task** +| ID| Error Message | +| -------- | ------------------------------------------------------- | +| 10200018 | The task group does not exist when it is canceled. | + +**Example** ```ts @Concurrent function printArgs(args) { + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } console.log("printArgs: " + args); return args; } -async function taskpoolCancel() { - let task1 = new taskpool.Task(printArgs, 100); - let task2 = new taskpool.Task(printArgs, 200); - let task3 = new taskpool.Task(printArgs, 300); - let task4 = new taskpool.Task(printArgs, 400); - let task5 = new taskpool.Task(printArgs, 500); - let task6 = new taskpool.Task(printArgs, 600); - - let res1 = taskpool.execute(task1); - let res2 = taskpool.execute(task2); - let res3 = taskpool.execute(task3); - let res4 = taskpool.execute(task4); - let res5 = taskpool.execute(task5); - let res6 = taskpool.execute(task6); +let taskGroup1 = new taskpool.TaskGroup(); +taskGroup1.addTask(printArgs, 10); // 10: test number +let taskGroup2 = new taskpool.TaskGroup(); +taskGroup2.addTask(printArgs, 100); // 100: test number +taskpool.execute(taskGroup1).then((res)=>{ + console.info("taskGroup1 res is:" + res) +}); +taskpool.execute(taskGroup2).then((res)=>{ + console.info("taskGroup2 res is:" + res) +}); +setTimeout(()=>{ try { - taskpool.cancel(task1); // task1 is being executed and fails to be canceled. + taskpool.cancel(taskGroup2); } catch (e) { - console.log("taskpool.cancel occur error:" + e); + console.log("taskGroup.cancel occur error:" + e); } -} - -taskpoolCancel(); +}, 1000); ``` ## Additional Information @@ -359,7 +631,7 @@ taskpoolExecute(); ```ts // b.ets -export var c = 2000; +export let c = 2000; ``` ```ts // Reference an imported variable. @@ -420,8 +692,8 @@ function strSort(inPutArr) { export async function func1() { console.log("taskpoolTest start"); let strArray = ['c test string', 'b test string', 'a test string']; - var task = new taskpool.Task(strSort, strArray); - var result = await taskpool.execute(task); + let task = new taskpool.Task(strSort, strArray); + let result = await taskpool.execute(task); console.log("func1 result:" + result); } @@ -435,9 +707,132 @@ export async function func2() { ``` ```ts -/ / a.ets (in the same directory as c.ets) +// a.ets (in the same directory as c.ets) import { taskpoolTest1, taskpoolTest2 } from "./c"; func1(); func2(); ``` + +**Example 5** + +```ts +// Success in canceling a task +@Concurrent +function inspectStatus(arg) { + // Check the task cancellation state and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // Wait for 2s. + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the task cancellation state again and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; +} + +async function taskpoolCancel() { + let task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res)=>{ + console.log("taskpool test result: " + res); + }).catch((err) => { + console.log("taskpool test occur error: " + err); + }); + // Cancel the task 1s later. + setTimeout(()=>{ + taskpool.cancel(task);}, 1000); +} + +taskpoolCancel(); +``` + +**Example 6** + +```ts +// Failure to cancel a task that has been executed +@Concurrent +function inspectStatus(arg) { + // Check the cancellation status and return the result. + if (taskpool.Task.isCanceled()) { + return arg + 2; + } + // Wait for 2s. + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the cancellation status again and return the result. + if (taskpool.Task.isCanceled()) { + return arg + 3; + } + return arg + 1; +} + +async function taskpoolCancel() { + let task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res)=>{ + console.log("taskpool test result: " + res); + }).catch((err) => { + console.log("taskpool test occur error: " + err); + }); + setTimeout(()=>{ + try { + taskpool.cancel(task); // The task has been executed and fails to be canceled. + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } + }, 3000); // Wait for 3s to ensure that the task has been executed. +} + +taskpoolCancel(); +``` + +**Example 7** + +```ts +// Success of canceling a task group to be executed +@Concurrent +function printArgs(args) { + let t = Date.now(); + while (Date.now() - t < 1000) { + continue; + } + console.log("printArgs: " + args); + return args; +} + +async function taskpoolGroupCancelTest() { + let taskGroup1 = new taskpool.TaskGroup(); + taskGroup1.addTask(printArgs, 10); // 10: test number + taskGroup1.addTask(printArgs, 20); // 20: test number + taskGroup1.addTask(printArgs, 30); // 30: test number + let taskGroup2 = new taskpool.TaskGroup(); + let task1 = new taskpool.Task(printArgs, 100); // 100: test number + let task2 = new taskpool.Task(printArgs, 200); // 200: test number + let task3 = new taskpool.Task(printArgs, 300); // 300: test number + taskGroup2.addTask(task1); + taskGroup2.addTask(task2); + taskGroup2.addTask(task3); + taskpool.execute(taskGroup1).then((res) => { + console.info("taskpool execute res is:" + res); + }).catch((e) => { + console.error("taskpool execute error is:" + e); + }); + taskpool.execute(taskGroup2).then((res) => { + console.info("taskpool execute res is:" + res); + }).catch((e) => { + console.error("taskpool execute error is:" + e); + }); + + taskpool.cancel(taskGroup2); +} + +taskpoolGroupCancelTest() +``` diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 7c74cdefcec7c61d2d2731ab64eae2f092a340ec..6d1bff42d490701f87940606d1ae4332b339b260 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -161,9 +161,9 @@ In the stage model: ### postMessage9+ -postMessage(message: Object, transfer: ArrayBuffer[]): void; +postMessage(message: Object, transfer: ArrayBuffer[]): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership. **System capability**: SystemCapability.Utils.Lang @@ -171,8 +171,8 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the worker thread. After the transfer, the objects are available only in the worker thread. The array cannot be null.| **Error codes** @@ -181,7 +181,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -196,7 +196,7 @@ workerInstance.postMessage(buffer, [buffer]); postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership or copying data. **System capability**: SystemCapability.Utils.Lang @@ -204,8 +204,8 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the worker thread and becomes unavailable in the host thread. The objects are available only in the worker thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the worker thread by copying data.| **Error codes** @@ -214,7 +214,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -617,7 +617,7 @@ workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is n // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will be always valid and will not be proactively deleted. +// The event listener created by addEventListener will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -792,7 +792,7 @@ workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is n // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will be always valid and will not be proactively deleted. +// The event listener created by addEventListener will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -849,16 +849,16 @@ Implements communication between the worker thread and the host thread. The **po postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------- | -| message | Object | Yes | Message to be sent to the host thread. | -| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.| **Error codes** @@ -867,7 +867,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -897,7 +897,7 @@ workerPort.onmessage = function(e){ postMessage(messageObject: Object, options?: PostMessageOptions): void -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership or copying data. **System capability**: SystemCapability.Utils.Lang @@ -905,8 +905,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the host thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the worker thread. The objects are available only in the host thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.| **Error codes** @@ -915,7 +915,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -1256,9 +1256,9 @@ In the stage model: ### postMessage(deprecated) -postMessage(message: Object, transfer: ArrayBuffer[]): void; +postMessage(message: Object, transfer: ArrayBuffer[]): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. @@ -1267,10 +1267,10 @@ Sends a message to the worker thread. The data type of the message must be seque **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ----------------------------------------------- | -| message | Object | Yes | Message to be sent to the worker thread. | -| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instances that can be transferred.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the worker thread. After the transfer, the objects are available only in the worker thread. The array cannot be null.| **Example** @@ -1285,7 +1285,7 @@ workerInstance.postMessage(buffer, [buffer]); postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership or copying data. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9-1) instead. @@ -1296,8 +1296,8 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the worker thread and becomes unavailable in the host thread. The objects are available only in the worker thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the worker thread by copying data.| **Example** @@ -1696,7 +1696,7 @@ Implements communication between the worker thread and the host thread. The **po postMessage(messageObject: Object, transfer: Transferable[]): void; -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership. > **NOTE**
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-2). @@ -1707,14 +1707,14 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| messageObject | Object | Yes | Message to be sent to the host thread. | +| messageObject | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| | transfer| Transferable[] | Yes | Currently, this parameter is not supported. | ### postMessage9+ postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership. > **NOTE** > @@ -1724,10 +1724,10 @@ Sends a message to the host thread from the worker thread. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ----------------------------------------------------- | -| message | Object | Yes | Message to be sent to the host thread. | -| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.| **Example** @@ -1756,7 +1756,7 @@ parentPort.onmessage = function(e){ postMessage(messageObject: Object, options?: PostMessageOptions): void -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership or copying data. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-3). @@ -1767,8 +1767,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the host thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the worker thread. The objects are available only in the host thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.| **Example** @@ -1893,7 +1893,7 @@ parentPort.onmessageerror = function(e) { ## PostMessageOptions -Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**. +Defines the object for which the ownership is to be transferred during data transfer. The object must be an **ArrayBuffer** instance. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver. **System capability**: SystemCapability.Utils.Lang @@ -2091,19 +2091,20 @@ workerPort.onerror = function(e) { ``` ### Memory Model -The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through sequentialization. They complete computing tasks and return the result to the main thread. +The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through serialization. They complete computing tasks and return the result to the main thread. Each actor concurrently processes tasks of the main thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the main thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently. ### Precautions -- Currently, a maximum of seven workers can co-exist. +- Currently, a maximum of eight workers can co-exist. - In API version 8 and earlier versions, when the number of **Worker** instances exceeds the upper limit, the error "Too many workers, the number of workers exceeds the maximum." is thrown. -- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum" is thrown. +- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum." is thrown. - To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. - Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). - When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file. +- A maximum of 16 MB data can be transferred during inter-thread communication. ## Sample Code > **NOTE**
diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 17cecd628287a774ab6070bbc0d40528bb7c108d..c1cd550641f09914fe47fafba4a38b84a03513c0 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -236,7 +236,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| -| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| +| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten.| | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -259,9 +259,7 @@ import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFileDir = '/xxx'; let options = { - level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, - memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, - strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION }; try { @@ -288,7 +286,7 @@ Decompresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| -| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| +| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten.| | options | [Options](#options) | Yes | Decompression parameters. | **Error codes** @@ -308,9 +306,7 @@ import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFileDir = '/xxx'; let options = { - level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, - memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, - strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION }; try { diff --git a/en/application-dev/reference/errorcodes/errorcode-utils.md b/en/application-dev/reference/errorcodes/errorcode-utils.md index 5301d298d0b95a5806c20a1f28151a8272193e3d..a744e667e9ff98b05686b997711d8022224c2ffc 100644 --- a/en/application-dev/reference/errorcodes/errorcode-utils.md +++ b/en/application-dev/reference/errorcodes/errorcode-utils.md @@ -100,7 +100,7 @@ Use a supported API. **Error Message** -Serializing an uncaught exception failed. +An exception occurred during serialization. **Description** @@ -246,7 +246,7 @@ Check the functions required by the tasks executed by the task pool and add the **Error Message** -The task is not exist when cancel it. +The task does not exist when it is canceled. **Description** @@ -258,13 +258,13 @@ The task to cancel does not exist in the task pool. **Solution** -Before canceling a task, ensure that the task is placed into the task pool by calling **taskpool.execute**. +Before canceling a task, ensure that the task has been placed in the task pool by calling **taskpool.execute** and is not finishing. If you are not sure, capture exceptions. ## 10200016 Failed to Cancel a Task Being Executed **Error Message** -The task is running when cancel it. +The task is executing when it is canceled. **Description** @@ -276,7 +276,7 @@ The task to cancel is being executed. **Solution** -Before canceling a task, ensure that the task finishes execution. +Before canceling a task, ensure that the task has been placed in the task pool by calling **taskpool.execute** and has not started execution. If you are not sure, capture exceptions. ## 10200017 Failed to Delete an Element That Does Not Exist @@ -295,3 +295,21 @@ The element to delete does not exist in the container. **Solution** Before deleting an element, ensure that the element exists in this container. + +## 10200018 Failed to Cancel a Task Group That Does Not Exist + +**Error Message** + +The task group does not exist when it is canceled. + +**Description** + +This error code is reported when you attempt to cancel a task group that does not exist. + +**Possible Causes** + +The task group to cancel does not exist in the task pool. + +**Solution** + +Before canceling a task group, ensure that the task group is placed in the task pool by calling **taskpool.execute** and is not finishing. If you are not sure, capture exceptions.