ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Understanding the BackgroundWorker Component
Subject:   Complex example?
Date:   2005-12-02 09:04:31
From:   redturtle
Response to: Complex example?

you are wrong... even this simple example CANNOT be done synchronously! It's a perfect example, that shows even a simple task (that take lots of processing time) should be done in a background thread.


IF you tried your method then the User Interface would be totally stuck between progress bar updates. Plus there would be no way to cancel the operation! The thread would be stuck in your "for loop" and therefore the user interface/cancel button will not work! until you are out of the "calculation loop". Sure you can check if "cancel" has been hit between iterations, but guess what? your program will not have any time to actually notice mouse clicks.. its stuck in your "summing loop".


It's a simple task, but its not how simple the task is, its how much cpu time it takes up. If I tell you to count to 1 trillion, and i also tell you, "you cannot do anything else in life, until you are done counting to 1 trillion" then you will quickly die of starvation.. you cannot eat, sleep, walk, work, talk until you are done counting to 1 trillion... same for this app, if you use single thread, you cannot process mouse clicks until you are done summing up the numbers.



If you do not trust me, try it out... try this app, all within the UI thread. You'll notice quickly, you cannot cancel, you'll be starving the UI.