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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Asynchronous Methods ❘ 145<br />

callback that it automatically invokes when the task has finished. One really nice feature of this “virtual<br />

callback” is that it executes on the UI thread so it can manipulate controls directly without using<br />

the form’s Invoke method.<br />

The AsyncAwait example program, which is available for download on this book’s website, is<br />

similar to the HandleCallback example program, but it uses the async and await keywords<br />

instead of a callback.<br />

The following code shows the event handler that executes when you click the program’s Count<br />

button. The async and await keywords are highlighted in bold.<br />

// Count on a separate thread.<br />

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

{<br />

// Disable the button.<br />

countButton.Enabled = false;<br />

countLabel.Text = "";<br />

countButton.Refresh();<br />

countLabel.Refresh();<br />

// Start the Count method on a new thread.<br />

Func countDelegate = Count;<br />

Task task = new Task(countDelegate, 5);<br />

task.Start();<br />

// Count to 3.<br />

for (int i = 1; i

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

Saved successfully!

Ooh no, something went wrong!