HarmonyOS鸿蒙Next中context在worker中传递报错(阻塞性问题)

HarmonyOS鸿蒙Next中context在worker中传递报错(阻塞性问题)

代码如下

@Sendable 
export default class InsertMsgDbModel { 
    public tableName: string = ''; 
    public dbName: string = ''; 
    public userId: string = GlobalConf.channel; 
    public sendableContext: sendableContextManager.SendableContext; 

    constructor(sendableContext: sendableContextManager.SendableContext) { 
        this.sendableContext = sendableContext; 
    } 
} 

let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context); 

const insertDbModel = new InsertMsgDbModel(sendableContext); 

private workerStage1: worker.ThreadWorker = new worker.ThreadWorker('ZhBaseLib/ets/workers/ZHBaseWorker.ets'); 

this.workerStage1.postMessage(insertDbModel); 

删除sendableContext 后可以正常传递,加上后提示序列化失败。按官方文档应该是支持的。

更多关于HarmonyOS鸿蒙Next中context在worker中传递报错(阻塞性问题)的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

可以参考官方示例:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-app-ability-sendablecontextmanager-V5#

使用场景

在worker线程中不支持直接使用getContext接口获取主线程的context信息。主线程和worker线程的上下文不一致。需要访问系统服务和资源时,需要将主线程的context发送消息的方式传输到worker线程中。参考链接:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md#native%E7%BB%91%E5%AE%9A%E5%AF%B9%E8%B1%A1

目前支持转换的Context包括Context、ApplicationContext、AbilityStageContext、UIAbilityContext。

请确认传入context是否为这四种类型

使用sendableContext需要配合使用postMessageWithSharedSendable方法,这边看您使用的是postMessage,可尝试替换为postMessageWithSharedSendable

sendableContextManager.convertFromContext的示例中使用的也是postMessageWithSharedSendable,请替换使用

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-worker-V5#postmessagewithsharedsendable12

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-app-ability-sendablecontextmanager-V5#sendablecontextmanagerconvertfromcontext

更多关于HarmonyOS鸿蒙Next中context在worker中传递报错(阻塞性问题)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,context在worker线程中传递时可能会出现阻塞性问题。这是由于worker线程和主线程之间的通信机制导致的。在鸿蒙系统中,context主要用于在不同组件之间传递数据和状态信息,但在worker线程中直接传递context可能会导致线程阻塞或数据不一致。

鸿蒙系统的worker线程设计为独立的执行环境,与主线程隔离,以确保异步任务的执行不会影响主线程的响应性。因此,直接在主线程和worker线程之间传递context可能会导致线程安全问题,进而引发阻塞或异常。

解决这一问题的方法是使用鸿蒙提供的线程间通信机制,如postTaskMessageSequence,来安全地在主线程和worker线程之间传递数据,而不是直接传递context。这样可以避免线程阻塞,并确保数据的正确传递。

具体实现时,可以将context中的必要数据提取出来,封装成消息或任务对象,然后通过postTaskMessageSequence发送到worker线程。在worker线程中接收到消息或任务后,再根据需要进行处理。这样可以确保线程间的通信是安全的,不会引发阻塞性问题。

在HarmonyOS鸿蒙Next中,如果在Worker线程中直接传递context对象,可能会遇到阻塞性问题,导致报错。这是因为context通常与主线程绑定,直接跨线程传递会引发线程安全问题。建议通过MessageEventBus等机制传递必要的数据,而非直接传递context对象。如果需要使用context,可以在Worker线程中通过AbilityContextContext的代理类进行安全操作。

回到顶部