在我的应用程序中,我将一个CFMachPortRef(通过CFMachPortCreateRunLoopSource)添加到线程CFRunLoop
现在我问自己,这可以使用 GCD 来完成吗?假设不是生成我自己的 NSThread 并通过 CFRunLoopAddSource 将创建的 CFRunLoopSourceRef 添加到其运行循环,而是将事件端口添加到调度的运行循环?
我认为由于 GCD 的内部工作原理,这很可能不起作用,但我真的不知道。
更新
<小时/>到目前为止我已经得到了这个,但是事件点击的回调函数和dispatch_source_event_handler block 都没有被调用。有什么想法吗?
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);
每当消息进入端口时,您作为事件处理程序传入的 block 都应该被调用,并且您可以在那里处理消息。此示例仅使用 GCD 提供的全局队列来处理消息,但如果您愿意,您可以创建自定义队列。
关于objective-c - GCD 和 RunLoop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3255428/