03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 20 ❘ 695<br />

client.DownloadString(urlTextBox.Text);<br />

}<br />

}<br />

catch (Exception ex)<br />

{<br />

MessageBox.Show(ex.Message);<br />

}<br />

3. The DownloadStringTaskAsync example program does this. The main change is to the<br />

Download button’s Click event handler shown in the following code. Notice the async<br />

and await keywords highlighted in bold.<br />

// Start downloading.<br />

async private void downloadButton_Click(object sender, EventArgs e)<br />

{<br />

// Get ready to give feedback.<br />

webBrowser1.Navigate("about:blank");<br />

downloadProgressBar.Value = 0;<br />

downloadStatusLabel.Text = "0%";<br />

downloadButton.Enabled = false;<br />

cancelButton.Enabled = true;<br />

Cursor = Cursors.WaitCursor;<br />

// Make a Uri.<br />

Uri uri = new Uri(urlTextBox.Text);<br />

// Start the download.<br />

Client = new WebClient();<br />

Client.DownloadProgressChanged += Client_DownloadProgressChanged;<br />

try<br />

{<br />

// Start the download.<br />

string result = await Client.DownloadStringTaskAsync(uri);<br />

// Display the result in the WebBrowser.<br />

webBrowser1.Document.Body.InnerHtml = result;<br />

}<br />

catch (WebException ex)<br />

{<br />

if (ex.Status == WebExceptionStatus.RequestCanceled)<br />

MessageBox.Show("Canceled");<br />

else<br />

MessageBox.Show(ex.Message);<br />

}<br />

catch (Exception ex)<br />

{<br />

MessageBox.Show(ex.Message);<br />

}<br />

Client.Dispose();<br />

// Remove the feedback.<br />

downloadProgressBar.Value = 0;<br />

downloadStatusLabel.Text = "";<br />

downloadButton.Enabled = true;<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!