The backgroundThread Entity
Listing 2 shows the class UploadContent.
Listing 2 The background thread.
public class UploadContent { public int numberOfBlocks = 5; public void UploadFirmware() { const int interBlockDelay = 1500; Console.WriteLine("Thread \"{0}\" is executing UploadContent.UploadFirmware()", Thread.CurrentThread.Name); // Do the content download. Console.WriteLine("Now executing the upload block transfers"); for(int i = 1; i <= numberOfBlocks; i++) { Console.WriteLine("Block {0} of {1}", i, numberOfBlocks); Thread.Sleep(interBlockDelay); } Console.WriteLine("Upload successful"); } }
We have a data member of type int called numberOfBlocks, and a single method called UploadFirmware() that does all the work, uploading packets to the selected device. Now, clearly, in Listing 2 I’m just making some calls to Console.WriteLine() and Thread.Sleep(). In a real implementation, this code would be making calls to external data transfer code—FTP, TFTP, etc.
The point to note about Listing 2 is that the upload code can be placed easily inside a separate thread of execution. This new thread of execution then leaves the main application free to do other work, as illustrated by the dialog box in Figure 2. However, from the perspective of a network manager, the approach we’ve taken so far has a substantial omission. As a wise thread once said: "Don’t call us, we’ll call you."
Can you think of anything that’s missing from the code so far? One significant element would be needed in a real-world setup: asynchronous behavior. The problem with the code in Listings 1 and 2 is that the main calling process won’t be informed of the completion of the threaded task. We’ve gone some of the way toward making the upload procedure asynchronous, but we haven’t achieved a proper separation of concerns. To separate the tasks, we can use an entity called the System.AsyncCallback delegate. The purpose is to ensure that the upload code informs us when the operation is finished. Also, since this is a network operation, it’s important to note that the operation in question may not always be successful.