在我的应用程序中我添加了一个CFMach端口参考 (via CFMachPortCreateRunLoopSource) 到线程CF运行循环
现在我问自己,这可以使用 GCD 来完成吗?让我们说,而不是生成我自己的NSThread并添加创建的CFRunLoop 源参考通过其运行循环CFRunLoop添加源,将事件端口添加到调度的运行循环中?
我认为由于 GCD 的内部工作原理,这很可能不起作用,但我真的不知道。
Update
到目前为止我已经得到了这个,但是事件点击的回调函数和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);
您实际上可以使用 GCD 来监视 Mach 端口,使用dispatch_source_create()
功能。代码看起来像这样:
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 提供的全局队列来处理消息,但如果您愿意,您可以创建自定义队列。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)