I had originally planned to continue my Simple Multithreading series, but there are some other things I need to cover before I start talking about using multiple processing threads. So that project will be delayed a bit until I have a bit of time to think things through. But on a related note . . .
I’m not sure why, but it seems that beginners often don’t get the point of asynchronous processing. For example, a common question is how to use WebClient.DownloadFileAsync to download a file in the background. The code that accompanies the question often looks something like this:
// at class scope
private ManualResetEvent DownloadDone = new ManualResetEvent(false);
private void SomeMethod()
{
// initialize WebClient instance
WebClient client = new WebClient();
// set event handlers
client.DownLoadFileCompleted += DownloadCompleted;
// clear completed flag
DownloadDone.Reset();
// start the download
client.DownloadFileAsync("http://whatever", "filename.pdf");
// wait for the download to complete
DownloadDone.WaitOne();
// Do other stuff
}
// and the completed handler
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
// do end-of download stuff
// then set event to indicate completion
DownloadDone.Set();
}
The code works, but using the asynchronous download isn’t doing any good because the main thread is waiting for the download to complete. The programmer could have saved himself some work by simply writing:
client.DownloadFile("http://whatever", "filename.pdf");
// Do other stuff
The whole point of starting an asynchronous download is to do something else while the file is being downloaded. At some point in the future, when you need the file that’s being downloaded, you check to see if it’s done. The right way to do it is:
// start the download
client.DownloadFileAsync("http://whatever", "filename.pdf");
// Do other stuff
// wait for the download to complete
DownloadDone.WaitOne();
// Do stuff that depends on the result of the download
There’s no doubt that the ability to download files asynchronously is cool, but don’t go through the effort of setting up an asynchronous download if your program can’t proceed until the download is done.
I find it surprising that beginners make this particular mistake. I also find it surprising that many find it difficult to understand why the first method is wrong. There is a fundamental piece missing somewhere in the way we teach programming (or perhaps in the way that many learn programming) that leaves a blind spot or a fixation on sequential processing. There has to be some way we can correct that. I just don’t yet know what it is.