1

I am porting an app reading data from a BT device to Mac. On the mac-specific code, I have a class with the delegate methods for the BT callbacks, like -(void) rfcommChannelData:(...)

On that callback, I fill a buffer with the received data. I have a function called from the app:

-(int) m_timedRead:(unsigned char*)buffer length:(unsigned long)numBytes time:(unsigned int)timeout
{

double steps=0.01;
double time = (double)timeout/1000;
bool ready = false;
int read,total=0;
unsigned long restBytes = numBytes;
while(!ready){
    unsigned char *ptr = buffer+total;
    read = [self m_readRFCOMM:(unsigned char*)ptr length:(unsigned long)restBytes];
    total+=read;
    if(total>=numBytes){
        ready=true; continue;
    }
    restBytes = numBytes-total;
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, .4, false);       
    time -= steps;
    if(time<=0){
        ready=true; continue;
    }
}

My problem is that this RunLoop makes the whole app un extremely slow. If I don't use default mode, and create my on runloop with a runlooptimer, the callback method rfcommChannelData never gets called. I create my one runloop with the following code:

//  CFStringRef myCustomMode = CFSTR("MyCustomMode");
//  CFRunLoopTimerRef myTimer;
//  myTimer = CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+1.0,1.0,0,0,foo,NULL);   
//  CFRunLoopAddTimer(CFRunLoopGetCurrent(), myTimer, myCustomMode);
//  CFRunLoopTimerInvalidate(myTimer);
//  CFRelease(myTimer);

Any idea why the default RunLoop slows down the whole app, or how to make my own run loop allow callbacks from rfcommchannel being triggered?

Many thanks,

Anton Albajes-Eizagirre

4

1 回答 1

1

如果您正在处理 GUI 应用程序的主线程,请不要在您自己的方法内部运行运行循环。安装运行循环源(或允许框架的异步 API 代表您安装源)并返回主事件循环。也就是说,让执行流程从您的代码中返回并返回给您的调用者。主事件循环运行主线程的运行循环,当源准备好时,它们的回调将触发,这可能会调用您的方法。

于 2012-04-27T23:33:36.203 回答