1# Worker同步调用宿主线程的接口 2<!--Kit: ArkTS--> 3<!--Subsystem: CommonLibrary--> 4<!--Owner: @lijiamin2025--> 5<!--Designer: @weng-changcheng--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @ge-yafang--> 8 9如果一个接口已在宿主线程中实现,Worker可以通过以下方式调用该接口。 10 11以下示例展示了Worker同步调用宿主线程接口的方法,创建worker的方法可参考[创建worker的注意事项](worker-introduction.md#创建worker的注意事项)。 12 131. 首先,在宿主线程实现需要调用的接口,并创建Worker对象,在Worker对象上注册需要调用的对象。 14 15 ```ts 16 // Index.ets 17 import { MessageEvents, worker } from '@kit.ArkTS'; 18 19 class TestObj { 20 public getMessage(): string { 21 return "this is a message from TestObj"; 22 } 23 24 static testObj: TestObj = new TestObj(); 25 } 26 27 @Entry 28 @Component 29 struct Index { 30 @State message: string = 'Hello World'; 31 32 build() { 33 Row() { 34 Column() { 35 Text(this.message) 36 .fontSize(50) 37 .fontWeight(FontWeight.Bold) 38 .onClick(() => { 39 // 创建Worker对象 40 const workerInstance: worker.ThreadWorker = new worker.ThreadWorker("entry/ets/workers/Worker.ets"); 41 // 在Worker上注册需要调用的对象 42 workerInstance.registerGlobalCallObject("testObj", TestObj.testObj); 43 workerInstance.postMessage("start"); 44 workerInstance.onmessage = (e: MessageEvents): void => { 45 // 接收Worker子线程的结果 46 console.info("mainthread: " + e.data); 47 // 销毁Worker 48 workerInstance.terminate(); 49 } 50 }) 51 } 52 .width('100%') 53 } 54 .height('100%') 55 } 56 } 57 ``` 58 <!-- @[create_worker_obj](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/managers/WorkerCallGlobalUsage.ets) --> 59 602. 然后,在Worker中通过callGlobalCallObjectMethod接口可以调用宿主线程中的getMessage()方法。 61 62 ```ts 63 // Worker.ets 64 import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; 65 66 const workerPort: ThreadWorkerGlobalScope = worker.workerPort; 67 68 workerPort.onmessage = async (e: MessageEvents) => { 69 if (e.data === 'start') { 70 try { 71 // 调用方法 72 let res: string = workerPort.callGlobalCallObjectMethod("testObj", "getMessage", 0) as string; 73 console.info("worker: ", res); 74 if (res === "this is a message from TestObj") { 75 workerPort.postMessage("run function success."); 76 } 77 } catch (error) { 78 // 异常处理 79 console.error("worker: error code is " + error.code + " error message is " + error.message); 80 } 81 } 82 } 83 ``` 84 <!-- @[call_main_method](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/workers/Worker.ets) --> 85