The name of the function beginBackgroundTask
appears to imply that it is safe to call from a background thread.
However, because this is part of the UIApplication
class, it causes a dispatch to the main thread first. This dispatch can prove problematic as it can introduce resource contention, or at worst deadlocks, if you're not very careful about how you're starting your task.
Example:
- Main thread calls a lower layer of code, which is using a dispatch queue to process operations
- An item in that queue is already processing an item which happens to call
beginBackgroundTask()
If the operation being performed on the main thread is synchronous, you get a deadlock. If the operation is asynchronous, you can still run into a delay if your background queue performs a lot of operations, as each one briefly is blocking the main queue each time.
The docs for beginBackgroundTask()
claim that invoking the API is asynchronous, or that you can call this method at any time, but that doesn't appear to actually be the case.
Was this by design? Is beginBackgroundTask()
intended to be used very sparingly?