Writing Mobile Code Essential Software Engineering for Building Mobile Applications [Electronic resources]

Ivo Salmre

نسخه متنی -صفحه : 159/ 67
نمايش فراداده

Introduction: When and How to Use Background Threads

Because devices are used frequently but for small amounts of time, users demand highly responsive experiences when using mobile software. Put simply, users do not want to waste time waiting for an application to respond to them. When used properly, a background thread can aid foreground responsiveness. The ability to create and use background threads is a powerful feature for building sophisticated mobile applications. This power brings with it both good and bad news.

First the bad news: Take it as a rule with very few exceptions, extra threads will not make your code run faster. In an absolute sense, additional threads will almost always make your code run slower. This is because you are giving the operating system one more stream of execution that it needs to manage and periodically switch control in and out of. This switching between execution streams has a performance penalty.

More bad news: Using background threads increases the complexity of your application significantly and has the potential to produce timing-related bugs. Timing-related bugs are notoriously difficult to track down. When first experimenting with threads, it is easy to see them as the answer to every problem regardless of actual need. As soon as developers master the basics of background threading, there is an inclination to become a bit "thread happy" and find reason after reason to create and utilize background threads. This tendency to overuse threads is even more pronounced when working on a project as a group; everyone has a task for which they would like their own isolated background thread in which to do their work free of the need to share execution with any other code. This sounds like a workable idea until all the pieces of code are run together and the application now has seven threads running concurrently doing all kinds of fascinating but unnecessary things. Extra threads that are not absolutely necessary drag down performance and increase an application's complexity. For good mobile application performance, developers working in groups need to find a way to efficiently distribute or queue tasks among a very limited number of threads.