GCD和RunLoops [英] GCD and RunLoops

查看:243
本文介绍了GCD和RunLoops的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my app I add an CFMachPortRef (via CFMachPortCreateRunLoopSource) to a threads CFRunLoop

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

Now i was asking myself, can this be done using GCD? Let's say instead of spawning my own NSThread and add the created CFRunLoopSourceRef to its run loop via CFRunLoopAddSource, add the event port to a dispatch's runloop?

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

I think this will most likely not work due to the inner workings of GCD, but I really don't know.

更新

到目前为止,我还是知道了,但是既没有调用事件tap的回调函数,也没有调用dispatch_source_event_handler块.有什么想法吗?

I got this so far, however neither the callback function for the event tap nor the dispatch_source_event_handler block is called. Any ideas?

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端口.代码看起来像这样:

You can actually use GCD to monitor a Mach port, using the dispatch_source_create() function. The code would look something like this:

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提供的全局队列来处理消息,但是您可以根据需要创建一个自定义队列.

Whenever a message comes into the port, the block you pass in as the event handler should get called, and you can handle the message there. This example just uses the global queue provided by GCD to handle the message, but you can create a custom queue if you'd like.

这篇关于GCD和RunLoops的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆