I’m using GCD to do some background loading from the internet. This works great except for a little flaw. In my app I have 3 tabs and when clicking on any tab the GCD starts to do the background loading for the appropriate tab. If the user decides to go from the first tab to the second tab (when the GCD has started downloaded data for the first tab) and then returns to the first tab again. GCD will start another background thread (even though the first background thread hasn’t finished downloaded the data yet).
So is there a way to check if a background thread is currently running? So that it doesn’t start multiple background threads if the user would choose to switch tabs back and forth very quickly (for some reason).
If you wanted to prevent two blocks of the same type from running at the same time, you could use a dispatch semaphore. With a semaphore set to a count of 1, you can check the semaphore before firing off the block and bail if something is still running. At the end of the block, you signal the semaphore to allow other blocks to be submitted.
I do this in one of my applications to prevent more than one OpenGL ES frame rendering block to be added to the queue at once (preventing buildup of blocks in the queue if a frame takes longer than 1/60th of a second to render). I describe some of this in my answer here, using the following code:
where
frameRenderingSemaphoreis created earlier as follows:If you create a similar semaphore for each tab’s download operations, you could do a check to make sure that more than one download isn’t being queued up at a time for that tab.