在我的应用程序中,我将CFMachPortRef(通过CFMachPortCreateRunLoopSource)添加到线程CFRunLoop中

现在我问自己,这可以使用GCD吗?假设不是生成我自己的NSThread并通过CFRunLoopAddSource将创建的CFRunLoopSourceRef添加到其运行循环中,而是将事件端口添加到调度程序的runloop中?

我认为由于GCD的内部功能,这很可能行不通,但我真的不知道。

更新资料



到目前为止,我还是明白了,但是既没有调用事件tap的回调函数,也没有调用dispatch_source_event_handler块。有任何想法吗?

CFMachPortRef port = CGEventTapCreate(kCGSessionEventTap,
                                      kCGHeadInsertEventTap,
                                      opts,
                                      desc_.eventMask,
                                      _CGEventCallback,
                                      self);

// create dispatch source
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV,
                                                  CFMachPortGetPort(port),
                                                  0,
                                                  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));

// set event handler
dispatch_source_set_event_handler(source, ^{
    printf("handle me!\n");
});

dispatch_resume(source);

最佳答案

实际上,您可以使用dispatch_source_create()功能使用GCD来监视Mach端口。代码看起来像这样:

mach_port_t myPort; //assume you have this already
dispatch_source_t portSource;

portSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, myPort, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT));
dispatch_source_set_event_handler(portSource, ^(void) { //code for handling incoming message here });

dispatch_resume(portSource);


每当消息进入端口时,您作为事件处理程序传递的块都将被调用,您可以在那里处理消息。本示例仅使用GCD提供的全局队列来处理消息,但是您可以根据需要创建自定义队列。

关于objective-c - GCD和RunLoops,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3255428/

10-13 05:50