CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
private void btnDownload_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s, eArgs) =>
{
theEBook = eArgs.Result;
txtBook.Text = theEBook;
};
// The Project Gutenberg EBook of A Tale of Two Cities, by Charles Dickens
wc.DownloadStringAsync(new Uri("http://www.gutenberg.org/files/98/98-8.txt"));
}
The WebClient class is a member of System.Net. This class provides a number of methods for
sending data to and receiving data from a resource identified by a URI. As it turns out, many of these
methods have an asynchronous version, such as DownloadStringAsync(). This method will spin up a new
thread from the CLR thread pool automatically. When the WebClient is done obtaining the data, it will
fire the DownloadStringCompleted event, which you are handling here using a C# lambda expression. If
you were to call the synchronous version of this method (DownloadString()) the form would appear
unresponsive for quite some time.
The Click event hander for the btnGetStats Button control is implemented to extract out the
individual words contained in theEBook variable, and then pass the string array to a few helper functions
for processing as follows:
private void btnGetStats_Click(object sender, EventArgs e)
{
// Get the words from the e-book.
string[] words = theEBook.Split(new char[]
{ ' ', '\u000A', ',', '.', ';', ':', '-', '?', '/' },
StringSplitOptions.RemoveEmptyEntries);
// Now, find the ten most common words.
string[] tenMostCommon = FindTenMostCommon(words);
// Get the longest word.
string longestWord = FindLongestWord(words);
// Now that all tasks are complete, build a string to show all
// stats in a message box.
StringBuilder bookStats = new StringBuilder("Ten Most Common Words are:\n");
foreach (string s in tenMostCommon)
{
bookStats.AppendLine(s);
}
}
bookStats.AppendFormat("Longest word is: {0}", longestWord);
bookStats.AppendLine();
MessageBox.Show(bookStats.ToString(), "Book info");
The FindTenMostCommon() method uses a LINQ query to obtain a list of string objects that occur
most often in the string array, while FindLongestWord() locates, well, the longest word.
739