CFReadStreamHasBytesAvailable polling - best practices

I'm currently polling my CFReadStream for new data with CFReadStreamHasBytesAvailable.

(First, some background: I'm doing my own threading and I don't want/need to mess with runloop stuff, so the client callback stuff doesn't really apply here).

My question is: what are accepted practices for polling?

Apple's documentation on the subject doesn't seem too helpful.

They recommend to "do something else while you wait". I'm currently just doing something along the lines of:

while(!done) { if(CFReadStreamHasBytesAvailable(readStream)) { CFReadStreamRead(...) ... bla bla bla } else { usleep(3600); // I made this up sched_yield(); // also made this up continue; } }

Is the usleep and the sched_yield "good enough"? In there a "good" number to sleep for in usleep?

(Also: yes, because this is running in my own thread, I could just block on CFReadStreamRead - which would be great but I'm also trying to snag upload progress as well as download progress, so blocking there wouldn't help...).

Any insight would be much appreciated - thanks!

-------------Problems Reply------------

I think this question is a bit of a paradox because you're asking what the best practices are for doing something that's intrinsically not a best practice ;)

When there's a perfectly good method for blocking on network I/O, any compromise that causes you to poll instead is by definition not the best practice.

That said, if you do poll I think it might be more appropriate to "run the runloop until date" on your thread, instead of using whatever posix sleep or yield method you're imagining. Remember that each thread gets its own runloop, so essentially by running the runloop you're allowing Apple to employ its concept of best practices for blocking until a future date.

As for the time delay, I don't know if you'll get a definitive answer for what a good time is. It's a tradeoff between peppering the CPU with polling cycles vs. being stuck in the runloop for a little while when I/O is ready to be read from the network.

Ideally I think I would refocus your efforts on making this work using I/O blocking calls, but if you stick with the poll & idle technique, don't fret too much about the specific delay time. Just pick something that works and doesn't seem to impact performance negatively in either direction.

(Also, I'd like to clarify that I'm not too religious about the polling vs. blocking thing, I'm only stressing its value because you're obviously in search of an elevated solution).

When doing manual CFStream based connections on a separate thread (for custom things like bandwidth monitoring and throttling), I use a combination of CFReadStreamScheduleWithRunLoop, CFRunLoopRunInMode and CFReadStreamSetClient. Basically I run for 0.25 seconds and then check stream status. The client callback also gets notified on its own as well. This allows me to periodically check read status and do some custom behavior but rely mostly on (stream) events.

static const CFOptionFlags kMyNetworkEvents =
| kCFStreamEventHasBytesAvailable
| kCFStreamEventEndEncountered
| kCFStreamEventErrorOccurred;

static void MyStreamCallBack(CFReadStreamRef readStream, CFStreamEventType type, void *clientCallBackInfo) {
[(id)clientCallBackInfo _handleNetworkEvent:type];

- (void)connect {

CFStreamClientContext streamContext = {0, self, NULL, NULL, NULL};
BOOL success = CFReadStreamSetClient(readStream_, kMyNetworkEvents, MyStreamCallBack, &streamContext);

CFReadStreamScheduleWithRunLoop(readStream_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);

if (!CFReadStreamOpen(readStream_)) {
// Notify error

while(!cancelled_ && !finished_) {

SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.25, NO);

if (result == kCFRunLoopRunStopped || result == kCFRunLoopRunFinished) {

if (([NSDate timeIntervalSinceReferenceDate] - lastRead_) > MyConnectionTimeout) {
// Call timed out

// Also handle stream status CFStreamStatus status = CFReadStreamGetStatus(readStream_);
if (![self _handleStreamStatus:status]) break;


CFReadStreamSetClient(readStream_, 0, NULL, NULL);
CFReadStreamUnscheduleFromRunLoop(readStream_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);



- (void)_handleNetworkEvent:(CFStreamEventType)type {
switch(type) {
case kCFStreamEventOpenCompleted:
// Notify connected

case kCFStreamEventHasBytesAvailable:
[self _handleBytes];

case kCFStreamEventErrorOccurred:
[self _handleError];

case kCFStreamEventEndEncountered:
[self _handleBytes];
[self _handleEnd];

Debug(@"Received unexpected CFStream event (%d)", type);

Category:iphone Views:0 Time:2009-02-28

Related post

  • Long Polling: Best practices using php/Jquery/json 2012-01-15

    guys i am planning to show my user live a flash message, whenever they get a new private message into their inbox. What is the best way to do it, using php 5.3, jquery,json and stuff like that? My favorite php framework is Symfony2 and javascript:Jqu

  • TUNTAP interface in C (Linux) : Can't capture UDP packets sent on the TUNTAP with sendto() 2012-02-21

    I am trying to write a tunneling program in C that will take UDP packets from a TUNTAP interface and send them to a serial interface. What I do is allocate the interface from the clone device /dev/net/tun, turn it on and give it an ip address : int t

  • Threading Practice with Polling 2010-04-30

    I have a C# application that has to constantly read from a program; sometimes there is a chance it will not find what it needs, which will throw an exception. This is a limitation of the program it has to read from. This frequently causes the program

  • What is the best practice when polling for sensor values? 2011-05-15

    I'm working on an application where I periodically need to get a sensor value. For this I'm using AlarmManager and a Receiver at set intervals. Android's sensor implementation seems to be focused around continuous reading of data, and it does not see

  • Polling data from server - most effecient and practical way/setup 2011-06-28

    I've been reading a few posts on here regarding polling and even had a look at Pusher although i don't want to go down that route and need some advice in regards of making an efficent notification system. How do facebook, twitter and other websites d

  • best practice for directory polling 2010-03-08

    I have to do batch processing to automate business process. I have to poll directory at regular interval to detect new files and do processing. While old files is being processed, new files can come in. For now, I use quartz scheduler and thread sync

  • Best practices for using Amazon SQS - Polling the queue 2010-04-20

    I'm designing a service for sending out emails for our eCommerce site (order confirmations, alerts etc...) The plan is to have a "SendEmail" method, that generates a chunk of XML representing the email to be sent, and sticks it on an Amazon SQS queue

  • WCF Async Calls Polling or Flagging - Best Practice 2010-07-29

    I'm working on this Silverlight 3.0 Project that is completely filled with Async Calls to a Web Service. At the Main Page it fetches some needed data in order for the application to work correctly using 3 Async Calls. Right now the application does n

  • Serial Port device protocol safe practice: Identification, polling 2011-07-01

    I'm creating a simple device that sends data to a Windows PC over serial COM ports. I'd like the software to be able to scan the available COM ports until it recognizes the device. The problem is, if the PC tries to initiate the handshake with a devi

  • Flex best practices? 2008-09-18

    I have the feeling that is easy to find samples, tutorials and simple examples on Flex. It seems harder to find tips and good practices based on real-life projects. Any tips on how to : How to write maintainable actionscript code How to ensure a clea

  • What is wrong with polling? 2008-11-26

    I have heard a few developers recently say that they are simply polling stuff (databases, files, etc.) to determine when something has changed and then run a task, such as an import. I'm really against this idea and feel that utilising available tech

  • Connecting a form to a Javascript Object (and other best practice advice) 2009-01-02

    I've been using javascript to do lightweight functionality on sites for years - DOM manipulation etc - but just now im beginning to investigate using it to do a lot more of the heavy lifting (in combo with PHP). I've only just started getting into OO

  • Is there an alternative of ajax that does not require polling without sever side modifications? 2009-01-09

    I'm trying to create a small and basic "ajax" based multiplayer game. Coordinates of objects are being given by a PHP "handler". This handler.php file is being polled every 200MS, by using ajax. Since there is no need to poll when nothing happens, I

  • SQL Server and application security models / best practice 2009-01-14

    For my web applications against sql server(at least the ones that require a logon to access) I generally implement security as follows: I generally roll my own user signup, user login pages and keep a userid and an encrypted password in an sq

  • URLLoader gets stuck when polling 2009-01-18

    Update: somehow this works when running flash in browser, but doesn't work if you run from IDE. You might want to try running in browser if you have the same problem. I am making a chat application that repeatedly reads a text file from my server usi

  • Is it practically safe to write static data from multiple threads 2009-02-26

    I have some status data that I want to cache from a database. Any of several threads may modify the status data. After the data is modified it will be written to the database. The database writes will always be done in series by the underlying databa

  • WinForms multi-threaded databinding scenario, best practice? 2009-03-02

    I'm currently designing/reworking the databinding part of an application that makes heavy use of winforms databinding and updates coming from a background thread (once a second on > 100 records). Let's assume the application is a stock trading app

  • Best practices for handling a web service failure 2009-03-16

    In an Ajax web app, what do you do when a web service call from the browser to your server fails? Automatically retry, hoping it was an intermittent network failure or server error. (But when you have a real server issue, you may face further problem

  • Is it better to poll or wait? 2009-06-02

    I have seen a question on why "polling is bad", but I am wonderring, in terms of minimizing the amount of processor time used by one thread, would it be better to do a spin wait (i.e. poll for a required change in a while loop) or wait on a kernel ob

Copyright (C), All Rights Reserved.

processed in 0.066 (s). 11 q(s)