CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
This is the commonest model and the one used throughout this book so far. It is illustrated in Figure 3:
In
the
Get data from a web service
Get data from a database
Do something else such as parsing an XML file
This
is the simplest threading model. The main thread is contained within the
Let's look at some code to demonstrate this. We'll use a form like the following:
When you click on a button, it will fire off a worker thread that will perform some calculations and return the results in the space below the buttons. We won't detail the UI code here; the full code can be downloaded from the https://www.Apress.com, but here are the relevant sections:
public class MainWorkerThe above methods are quite straightforward and are wrapped in a class for modularity reasons. The first returns an ArrayList containing all of the factors of the number passed to it, whereas the second simply returns a Long. Remember that factorials very quickly get very large. The factorial of 13 is 6,227,020,800. The factorial method doesn't tie up the processor for very long, but it can be used to illustrate this model.
public frmCalculate()The constructor just contains an instantiation of a new MainWorker object that will be used in the methods. Below we show the methods used for the button click event handlers:
The cmdFactors_Click() method instantiates a new thread with the FactorsThread() method, which formats and acts upon the result contained in MainWorker.CalculateFactors().
This method will need to be wrapped because thread methods cannot have return values.
private void cmdFactorial Click(object sender, System.EventArgs e)The FactorialThread() method is much simpler. Whenever the cmdFactorial button is clicked, the main thread fires off a new thread and updates the lblResult text label when the results have been achieved.
This was a straightforward example of main and worker threads in actions. Obviously, this example can easily be changed to deal with a connection to a database, or other more time-consuming activities.
However, you need to take care of several issues relating to threads when you use this mode. You can have threads spawning threads, threads accessing the same resource, and threads going into an infinite loop.
This is the simplest model, but also the one that requires most work from the developer.
In addition, the threads are completely independent of each other, each being controlled entirely by its parent - in this case the main thread.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 741
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved