一般常见多线程Context传递使用场景中,仅限于对Context中的资源进行读取,如果存在读写,可能存在并发安全问题,需要用到异步锁保证并发安全,不在本文中讨论。
一、多线程中传递Context上下文对象有以下常见场景:
import { worker } from '@kit.ArkTS';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
build() {
RelativeContainer() {
Text('向Worker线程传递上下文对象')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
let workerInstance: worker.ThreadWorker = new worker.ThreadWorker('../workers/Worker.ets');
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
workerInstance.postMessage(context);
} catch (error) {
console.error(JSON.stringify(error));
}
})
}
.height('100%')
.width('100%')
}
} import { MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (event: MessageEvents) => {
const contextWorker = event.data as Context;
try {
contextWorker.resourceManager.getStringValue($r('app.string.module_desc').id,
(error: BusinessError, value: string) => {
if (error != null) {
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
} else {
console.info(`worker msg: ${value}`);
}
});
} catch (error) {
console.info(JSON.stringify(error));
}
}; @Entry
@Component
struct TaskPoolDemo {
build() {
RelativeContainer() {
Text('TaskPool传递Context对象')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
taskpool.execute(getStringFromUIThread, context).catch((error: BusinessError) => {
console.error(`taskpool execute failed, error code: ${error.code}, message: ${error.message}.`);
});
})
}
.height('100%')
.width('100%')
}
} @Concurrent
async function getStringFromUIThread(context: Context) {
try {
context.resourceManager.getStringValue($r('app.string.module_desc').id, (error: BusinessError, value: string) => {
if (error != null) {
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
} else {
console.info(`worker msg: ${value}`);
}
});
} catch (error) {
console.error(JSON.stringify(error));
}
} import { common, sendableContextManager } from '@kit.AbilityKit';
import { worker } from '@kit.ArkTS';
@Sendable
class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
@Entry
@Component
struct SharedContextWorkerDemo {
build() {
RelativeContainer() {
Text('利用SendableContext传递')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let workerInstance: worker.ThreadWorker = new worker.ThreadWorker('../workers/TestWorker.ets');
let sendableContext: sendableContextManager.SendableContext =
sendableContextManager.convertFromContext(context);
let object: SendableObject = new SendableObject(sendableContext, 'UIAbilityContext');
try {
workerInstance.postMessageWithSharedSendable(object);
} catch (error) {
JSON.stringify(error);
}
})
}
.height('100%')
.width('100%')
}
} import { MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Sendable
class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let object: SendableObject = e.data;
let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
if (object.contextName == 'UIAbilityContext') {
try {
let context: common.UIAbilityContext = sendableContextManager.convertToUIAbilityContext(sendableContext);
context.resourceManager.getStringValue($r('app.string.module_desc').id,
(error: BusinessError, value: string) => {
if (error != null) {
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
} else {
console.info(`worker msg: ${value}`);
}
});
} catch (error) {
console.error(JSON.stringify(error));
}
}
}; 可以将Context对象直接转成SendableContext对象传给执行函数,在执行函数中再转成Context。
import { common, sendableContextManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { taskpool } from '@kit.ArkTS';
@Concurrent
async function getCacheDir(sendableContext: sendableContextManager.SendableContext) {
const contextTask: common.UIAbilityContext = sendableContextManager.convertToUIAbilityContext(sendableContext);
// 直接使用getContext方法时,主线程调用获取Context对象并可正常打印。子线程调用时无法获取Context对象
try {
contextTask.resourceManager.getStringValue($r('app.string.module_desc').id,
(error: BusinessError, value: string) => {
if (error != null) {
console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
} else {
console.info(`worker msg: ${value}`);
}
});
} catch (error) {
console.error(JSON.stringify(error));
}
}
@Entry
@Component
struct SharedContextTaskPoolDemo {
build() {
RelativeContainer() {
Text('TaskPool传递SendableContext对象')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let sendableContext = sendableContextManager.convertFromContext(context);
taskpool.execute(getCacheDir, sendableContext).catch((error: BusinessError) => {
console.error(`taskpool execute failed, error code: ${error.code}, message: ${error.message}.`);
});
})
}
.height('100%')
.width('100%')
}
} import { sendableContextManager } from '@kit.AbilityKit';
// 声明当前模块为共享模块,只能导出可Sendable数据
'use shared'
// 共享模块,SingletonA全局唯一
@Sendable
class SingletonShareContext {
private sendableContext: sendableContextManager.SendableContext | undefined;
init(context: Context) {
if (!this.sendableContext) {
this.sendableContext = sendableContextManager.convertFromContext(context);
}
}
// 返回sendableContext对象
public getContext() {
if (this.sendableContext === undefined) {
console.error('sendableContext未初始化');
}
return this.sendableContext;
}
}
export const singletonShareContext = new SingletonShareContext(); import { taskpool } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { singletonShareContext } from './SingletonShareContext';
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
async function printContext() {
// 将SendableContext对象转换为Context
let context: common.Context = sendableContextManager.convertToUIAbilityContext(singletonShareContext.getContext()!);
// 主线程和子线程调用时均可正常打印
console.info('sendableContextManager:' + context.cacheDir);
}
@Entry
@Component
struct SingletonSharedDemo {
aboutToAppear(): void {
singletonShareContext.init(this.getUIContext().getHostContext()!);
}
build() {
Row() {
Column({ space: 10 }) {
Button('MainThread print')
.onClick(async () => {
console.info('MainThread print');
printContext();
})
Button('TaskPool print')
.onClick(() => {
console.info('Taskpool print');
taskpool.execute(printContext).catch((error: BusinessError) => {
console.error(JSON.stringify(error));
});
})
}
.width('100%')
}
.height('100%')
}
} Q:为什么通过postMessage将SendableContext传递到Worker会报错?
A:postMessage只支持序列化对象。SendableContext对象是Sendable支持的数据类型,需要通过postMessageWithSharedSendable进行发送。
Q:postMessageWithSharedSendable和postMessage区别?
A:postMessage:宿主线程通过转移对象所有权或者拷贝数据的方式向Worker线程发送消息。
postMessageWithSharedSendable:宿主线程向Worker线程发送消息,消息中的Sendable对象通过引用传递,非Sendable对象通过序列化传递。