1.What happens to the active thread of my App when the App looses focus?
2. What if it is in an event handler at this moment?
3. What happens with async functions?
4. What happens to background threads that I have created with Task. Start?
3. What happens with async functions?
4. What happens to background threads that I have created with Task. Start?
5. In which state is the App when it regains focus, meaning not being restarted?
- All threads are suspended when the app goes to the background.
- If the UI thread is blocked then your app will likely be killed after a certain amount of time (maybe 20 seconds).
- Async functions are not special. They're just a compiler feature to break functions into smaller functions and chain them together. If you use
await
on the UI thread then it does not block the thread, which means you can avoid running into problems described in the previous answer. - Background threads are suspended and will resume when the app resumes.
- The app will be in the same state as you left it. However, active network connections will have been dropped so you have to be able to handle that.
The code will just stop running (kind of like when you break in the debugger). Once you resume the app the code starts up right where it left off.
The UI thread is different because when your app goes into the background there is an app delegate event to handle that. As a result the OS does wait for the UI thread to finish what it's doing (like if there's an active event handler) and return control to the event loop. However, if you fail to do that quickly then your app will be considered hung and it will be killed instead. That's one of many reason you should avoid doing anything that takes a long time in the UI thread.
If your state can be updated quickly (<1s) then do it in the UI thread when entering the background. If it takes longer then you can do it in the background and then use some iOS APIs to request a bit more time to let the asynchronous code finish before your app is suspended. On Android I think you don't have to do anything special.
No comments:
Post a Comment