46
Hands-On Lab Asynchronous Programming in the .NET Framework 4.5 Lab version: 1.2.0.0 Last updated: 2/6/2012

Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Hands-On LabAsynchronous Programming in the .NET Framework 4.5 Lab version: 1.2.0.0

Last updated: 2/6/2012

Page 2: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

CONTENTS

OVERVIEW................................................................................................................................................. 3

EXERCISE 1: THE ASYNC METHOD........................................................................................................4Task 1 – Creating the Application in the Old Way................................................................................5

Task 2 – Using Asynchronous Code....................................................................................................10

EXERCISE 2: CONCURRENT DOWNLOAD...........................................................................................12Task 1 – Adding Concurrent Download in a Separate Method..........................................................12

Task 2 – Verification...........................................................................................................................19

EXERCISE 3: POLLING AND CANCELLATION.....................................................................................20Task 1 – Adding the Cancellation Feature..........................................................................................20

Task 2 – Polling the Links Status........................................................................................................26

EXERCISE 4: ASYNC LIBRARY REFACTORING...................................................................................33Task 1 – Creating an Asynchronous Class Library..............................................................................33

Task 2 – Refactoring the Project........................................................................................................34

APPENDIX: USING CODE SNIPPETS.....................................................................................................38

To give feedback please write to [email protected] © 2011 by Microsoft Corporation. All rights reserved.

Page 3: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Overview

When your user interface is unresponsive or your server does not scale, chances are your code needs to be more asynchronous. Microsoft .NET Framework 4.5 introduces new language features in C# and Visual Basic to provide a new foundation for asynchrony in .NET programming. This new foundation makes asynchronous programming very similar to synchronous programming.

In this Hands-On Lab you will learn how to implement asynchronous programming with the new features introduced by Microsoft .NET Framework 4.5.

Introduction to Asynchronous Operations

Asynchronous operations are operations that are initiated and continue running concurrently with the invoking code.

When conforming to the .NET Task-Based Asynchronous Pattern (TAP), asynchronous methods return a task, which represents the ongoing operation and enables you to wait for its eventual outcome.

Invoking and then waiting asynchronously for a task-returning method to complete has been simplified to a single-line instruction: “await myAsyncMethod();”. With this new asynchronous model, the control flow is completely unaltered. What is more, there are no callbacks because the compiler takes care of creating and signing them up.

Throughout this lab, you will become more familiar with the implementation of simple asynchronous logic to prevent blocking the UI when performing remote calls or intensive CPU processing.

Note: You can find more references on .NET Asynchronous programming and the Task-Based Asynchronous Pattern at http://msdn.microsoft.com/async.

Objectives

In this hands-on lab, you will learn how to:

Convert synchronous code into asynchronous code

Perform tasks without blocking the UI

Run concurrent tasks

Implement cancellation and polling features

Generate a DLL library that exposes asynchronous methods

Page 4: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Prerequisites

Microsoft Visual Studio 11 Beta

Setup

Throughout the lab document, you will be instructed to insert code blocks. For your convenience, most of that code is provided as Visual Studio Code Snippets, which you can use from within Visual Studio to avoid having to add it manually.

To install the code snippets:

1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder.

2. Double-click the Setup.cmd file in this folder to install the Visual Studio Code Snippets.

If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document ‘Using Code Snippets’.

Exercises

This hands-on lab includes the following exercises:

1. The Async Method

2. Concurrent Download

3. Polling and Cancellation

4. Async Library Refactoring

Note: Each exercise is accompanied by a starting solution—located in the Begin folder of the exercise—that allows you to follow each exercise independently of the others. Please be aware that the code snippets that are added during an exercise are missing from these starting solutions and that they will not necessarily work until you complete the exercise.

Inside the source code for an exercise, you will also find an End folder containing a Visual Studio solution with the code that results from completing the steps in the corresponding exercise. You can use these solutions as guidance if you need additional help as you work through this hands-on lab.

Exercise 1: The Async Method

Page 5: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

In this exercise, you will create a very simple application that will download the HTML content of a web page and, using regular expressions, search through that content looking for any link. Then, you will display those links in a ListBox. You will build this application in two ways. First, you will build the application using synchronous code and examine the issues with this implementation. Second, you will modify that application to use the asynchronous code so you can see how this implementation addresses the issues with the first version of the application.

Task 1 – Creating the Application in the Old Way

In this task, you will create a WPF application to download a web page and find any link in the HTML. You will write the code in the old way by using synchronous calls, and finally, run the application to see the disadvantages of this way of programming.

1. Open Visual Studio 11 and create a new WPF Application project with the name AsyncLab. Choose the language of your preference: C# or Visual Basic.

2. In the MainWindow.xaml designer, resize the window to 640x480.

3. Drop a TextBox on the left to display the HTML and a ListBox on the right to display the found links.

4. Drop a button at the bottom and set its content to “Start”. You will get the following XAML code:

XAML

<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Width="640" Height="480"> <Grid> <TextBox Height="379" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="294" /> <ListBox Height="379" HorizontalAlignment="Right" Margin="0,12,12,0" Name="listBox1" VerticalAlignment="Top" Width="294" /> <Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="272,406,0,0" Name=“startButton” VerticalAlignment="Top" Width="75" /> </Grid></Window>

Note: Make sure you only copy the highlighted lines.

5. Double-click the Start button to create a Click event handler.

Page 6: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

6. Add code to disable the Start button while the work is in progress, and enable it once the work is completed.

(Code Snippet – Async Lab - Ex01 - Disable Enable Start - CS)

C#

private void startButton_Click(object sender, RoutedEventArgs e){ startButton.IsEnabled = false; startButton.IsEnabled = true;}

(Code Snippet – Async Lab - Ex01 - Disable Enable Start - VB)

Visual Basic

Private Sub startButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Start.Click

startButton.IsEnabled = False

startButton.IsEnabled = TrueEnd Sub

7. Define a list of strings to store the URIs at the beginning of the Start event.

(Code Snippet – Async Lab - Ex01 - URIs List - CS)

C#

private void startButton_Click(object sender, RoutedEventArgs e){ List<string> uris = new List<string>(); startButton.IsEnabled = false;

(Code Snippet – Async Lab - Ex01 - URIs List - VB)

Visual Basic

Private Sub startButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles startButton.Click

Dim uris As New List(Of String)() startButton.IsEnabled = False

Page 7: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

8. In between the code that disables and enables the Start button, insert a try-catch block for the main functionality of the application. Then, implement an exception handler to display a message box with the description of the error.

(Code Snippet – Async Lab - Ex01 - TryCatch - CS)

C#

List<string> uris = new List<string>();startButton.IsEnabled = false;

try{

} catch (Exception ex){ MessageBox.Show(ex.ToString());}

startButton.IsEnabled = true;

(Code Snippet – Async Lab - Ex01 - TryCatch - VB)

Visual Basic

Dim uris As New List(Of String)()startButton.IsEnabled = False

Try

Catch ex As Exception MessageBox.Show(ex.ToString())End Try

startButton.IsEnabled = True

9. Add a project reference to System.Net.

10. Import the following namespaces:

(Code Snippet – Async Lab - Ex01 - Namespaces - CS)

C#

using System.Net;using System.Text.RegularExpressions;

(Code Snippet – Async Lab - Ex01 - Namespaces - VB)

Page 8: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Visual Basic

Imports System.NetImports System.Text.RegularExpressions

11. Insert the following code to download the HTML content from a specific URL. Then, once it is downloaded, the result is assigned to the textbox value.

(Code Snippet – Async Lab - Ex01 - Download Page - CS)

C#

try{ WebClient client = new WebClient(); string result = client.DownloadString("http://msdn.microsoft.com");

textBox1.Text = result;}catch (Exception ex){ MessageBox.Show(ex.ToString());}

(Code Snippet – Async Lab - Ex01 - Download Page - VB)

Visual Basic

Try Dim client As New WebClient() Dim result As String = client.DownloadString("http://msdn.microsoft.com")

textBox1.Text = resultCatch ex As Exception MessageBox.Show(ex.ToString())End Try

12. Use a regular expression to search for links, store them in a URIs list, and then, bind the URIs list to the ListBox.

(Code Snippet – Async Lab - Ex01 - Search Links - CS)

C#

textBox1.Text = result;

MatchCollection mc = Regex.Matches(result,

Page 9: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

"href\\s*=\\s*(?:\"(?<1>http://[^\"]*)\")", RegexOptions.IgnoreCase);foreach (Match m in mc){ uris.Add(m.Groups[1].Value);} listBox1.ItemsSource = uris;

(Code Snippet – Async Lab - Ex01 - Search Links - VB)

Visual Basic

textBox1.Text = result

Dim mc As MatchCollection = Regex.Matches(result, "href\s*=\s*(?:\""(?<1>http://[^""]*)\"")", RegexOptions.IgnoreCase)For Each m As Match In mc uris.Add(m.Groups(1).Value)Next listBox1.ItemsSource = uris

13. Press F5 to start debugging. When the application starts, click the Start button.

Page 10: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Figure 1Running the application

Note: Notice the window is unresponsive and the button is not being disabled because the UI is blocked while the application is downloading the web page.

Task 2 – Using Asynchronous Code

In this task, you will enhance the application you have started in the previous task to make it asynchronous. To do this, you will implement an asynchronous method to download the page in the background.

1. Add a project reference to System.Net.Http.

2. Make the following change at the top of the code file:

C#

using System.Net.Http;using System.Text.RegularExpressions;

Page 11: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

(Code Snippet – Async Lab - Ex01 - Namespaces - VB)

Visual Basic

Imports System.Net.HttpImports System.Text.RegularExpressions

3. Add the async keyword in the startButton_Click function.

C#

private async void startButton_Click(object sender, RoutedEventArgs e){

Visual Basic

Private Async Sub startButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Start.Click

Note: The async keyword is one of the new keywords that .NET Framework 4.5 provides. The Async keyword communicates to the compiler that the current method will contain asynchronous code.

4. Replace the code that uses the WebClient class with the a call to the GetAsync method of the HttpClient class.

C#

try{ var response = new HttpClient().GetAsync("http://msdn.microsoft.com"); string result = await response.Content.ReadAsStringAsync();

textBox1.Text = result; ...

Visual Basic

Try Dim response = New HttpClient().GetAsync("http://msdn.microsoft.com") Dim result As String = response.Content.ReadAsStringAsync()

textBox1.Text = result

Page 12: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

...

Note: The GetAsync method returns a Task object. A Task object represents an asynchronous operation that may complete at some point in the future.

5. Add the await keyword on the call to GetAsync().

(Code Snippet – Async Lab - Ex01 - Download Page Async - CS)

C#

try{ var response = await new HttpClient().GetAsync("http://msdn.microsoft.com"); string result = await response.Content.ReadAsStringAsync();

textBox1.Text = result; ...

(Code Snippet – Async Lab - Ex01 - Download Page Async - VB)

Visual Basic

Try Dim response = Await New HttpClient().GetAsync("http://msdn.microsoft.com") Dim result As String = Await response.Content.ReadAsStringAsync ()

textBox1.Text = result ...

Note: When you add the await keyword, you are telling the compiler to asynchronously wait for the task returned by the method. This means that the rest of the code will be executed as a callback after the awaited method completes. You do not need to change your try-catch block in order to make this work. The exceptions that happen in the background or in the foreground will still be caught.

6. Press F5 to run the application and click the Start button. Notice that the application is responsive while the Start button is disabled. UI thread is never locked because the work is processed in the background.

Page 13: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Exercise 2: Concurrent Download

In this exercise, you will enhance the solution from Exercise 1 by enabling users to interact with the application while the contents are being downloaded. You will learn how to use the Task object in order to prevent blocking the user interface (UI).

After completing the exercise, the application will remain responsive while it downloads the full web page.

Task 1 – Adding Concurrent Download in a Separate Method

1. Open Visual Studio 11 and load AsyncLab-Ex2-Begin.sln solution located in the Source\[CS|VB]\Ex2-Concurrency\Begin folder of this lab. You can also continue working with the solution you’ve obtained after completing Exercise 1.

2. Open MainWindow.xaml.cs or MainWindow.xaml.vb code-behind and import the System.Collection.ObjectModel namespace.

C#

using System.Collections.ObjectModel;

Visual Basic

Imports System.Collections.ObjectModel

3. In startButton_Click event handler, replace the uris local variable type with an ObservableCollection type.

C#

private async void startButton_Click(object sender, RoutedEventArgs e){ List<string> uris = new List<string>(); ObservableCollection<string> uris = new ObservableCollection<string>(); startButton.IsEnabled = false;

try { ...

Visual Basic

Private Async Sub startButton_Click(sender As System.Object,

Page 14: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

e As System.Windows.RoutedEventArgs) Handles Start.Click

Dim uris As New List(Of String)() Dim uris As New ObservableCollection(Of String)() startButton.IsEnabled = False

4. Send the URI processing to the background in order to improve the application responsiveness. Enclose the filter and list manipulation logic into a lambda expression, which will be executed in background thread when calling Task.Run(). This task will be completed asynchronously, as it includes the await keyword.

(Code Snippet – Async Lab - Ex02 - AwaitBlock - CS)

C#

private async void startButton_Click(object sender, RoutedEventArgs e){ ... try { ... textBox1.Text = result;

await Task.Run(() => { MatchCollection mc = Regex.Matches( result, "href\\s*=\\s*(?:\"(?<1>http://[^\"]*)\")", RegexOptions.IgnoreCase); foreach (Match m in mc) { uris.Add(m.Groups[1].Value); } });

(Code Snippet – Async Lab - Ex02 - AwaitBlock - VB)

Visual Basic

Private Async Sub startButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Start.Click ... Try ... textBox1.Text = result Await Task.Run(Sub() Dim mc As MatchCollection = Regex.Matches(result, "href\s*=\s*(?:\""(?<1>http://[^""]*)\"")", RegexOptions.IgnoreCase)

Page 15: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

For Each m As Match In mc uris.Add(m.Groups(1).Value) Next End Sub)

Note: By using Task.Run, you are explicitly running your logic on a different thread from the thread pool.

5. Create a new class in the root of AsyncLab project and name it LinkInfo. This class will contain information about the links of the page. Insert the following code in the LinkInfo class.

(Code Snippet – Async Lab - Ex02 - LinkInfo - CS)

C#

namespace AsyncLab{ public class LinkInfo { public string Title { get; set; }

public string Html { get; set; }

public int Length { get; set; } }}

(Code Snippet – Async Lab - Ex02 - LinkInfo - VB)

Visual Basic

Public Class LinkInfo Public Property Title() As String

Public Property Html() As String

Public Property Length As IntegerEnd Class

6. Create a new method to download a page in the MainWindow.xaml.cs or MainWindow.csml.vb code-behind class. Name this method DownloadItemAsync and declare it with the Async prefix. This method will return an empty string in case the HTTP GET operation cannot be resolved.

(Code Snippet – Async Lab - Ex02 - DownloadItemAsync - CS)

Page 16: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

C#

private static async Task<LinkInfo> DownloadItemAsync(Uri itemUri){ string item; try { HttpClient httpClient = new HttpClient(); httpClient.MaxResponseContentBufferSize = 1000000; var response = await httpClient.GetAsync(itemUri); item = await response.Content.ReadAsStringAsync(); } catch { item = string.Empty; }

LinkInfo linkInfo = new LinkInfo { Length = item.Length, Title = GetTitle(item), Html = item }; return linkInfo;}

(Code Snippet – Async Lab - Ex02 - DownloadItemAsync - VB)

Visual Basic

Private Shared Async Function DownloadItemAsync( ByVal itemUri As Uri) As Task(Of LinkInfo)

Dim item As String Try Dim httpClient As New HttpClient httpClient.MaxResponseContentBufferSize = 1000000

Dim response = Await httpClient.GetAsync(itemUri) item = Await response.Content.ReadAsStringAsync() Catch item = String.Empty End Try

Dim linkInfo As LinkInfo = New LinkInfo() With { .Length = item.Length, .Html = item, .Title = GetTitle(item)}

Return linkInfoEnd Function

Page 17: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Note: Notice we are setting an arbitrary HTTP client buffer size, which is higher than the default value (~65Kb). This is because many web messages may exceed this value and generate an application error.

7. Create a GetTitle method after the DownloadItemAsync method to return the text located inside the title tag.

(Code Snippet – Async Lab - Ex02 - GetTitle - CS)

C#

private static string GetTitle(string html){ if (html.Length == 0) { return "Not Found"; }

Match m = Regex.Match(html, @"(?<=<title.*>)([\s\S]*)(?=</title>)", RegexOptions.IgnoreCase); return m.Value;}

(Code Snippet – Async Lab - Ex02 - GetTitle - VB)

Visual Basic

Private Shared Function GetTitle(ByVal html As String) As String If (html.Length.Equals(0)) Then Return "Not Found" End If

Dim m As Match = Regex.Match(Html, "(?<=<title.*>)([\s\S]*)(?=</title>)", RegexOptions.IgnoreCase) Return m.ValueEnd Function

8. Modify the startButton_Click event handler logic to use the DownloadItemAsync method and populate the ListBox with the retrieved items.

(Code Snippet – Async Lab - Ex02 - DownloadCompleted - CS)

C#

Page 18: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

private async void startButton_Click(object sender, RoutedEventArgs e){ ... try { ... await Task.Run(() => { MatchCollection mc = Regex.Matches(result, "href\\s*=\\s*(?:\"(?<1>http://[^\"]*)\")", RegexOptions.IgnoreCase); foreach (Match m in mc) { uris.Add(m.Groups[1].Value); } });

listBox1.ItemsSource = await Task.WhenAll( from uri in uris select DownloadItemAsync(new Uri(uri))); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }

(Code Snippet – Async Lab - Ex02 - DownloadCompleted - VB)

Visual Basic

Private Async Sub startButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Start.Click ... Try ... Await Task.Run(Sub() Dim mc As MatchCollection = Regex.Matches( result, "href\s*=\s*(?:\""(?<1>http://[^""]*)\"")", RegexOptions.IgnoreCase) For Each m As Match In mc uris.Add(m.Groups(1).Value) Next End Sub) listBox1.ItemsSource = Await Task.WhenAll( _ From uri In uris _ Select DownloadItemAsync(New Uri(uri)))

Page 19: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Catch ex As Exception MessageBox.Show(ex.ToString()) End Try ...End Sub

Note:

- When using Task.WhenAll, a task completes when all of the constituent tasks have completed. In this example, the await keyword before Task.WhenAll is forcing it to asynchronously wait for all of the items to complete before continuing the execution of the next instruction.

- When using Task.WhenAny, the returned task completes when any of the tasks completes.

9. Open MainWindow.xaml XAML view and insert the following code before the Grid to show the link title and the length of the linked page.

XAML

<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="480" Width="640"> <Window.Resources> <DataTemplate x:Key="DataTemplateItem"> <StackPanel Orientation="Horizontal"> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat=" {0} - {1} "> <Binding Path="Length"/> <Binding Path="Title"/> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </DataTemplate> </Window.Resources> <Grid>...

10. Modify the ListBox to use the data template from the previous step.

XAML

<Grid> <TextBox Height="379" HorizontalAlignment="Left" Margin="12,12,0,0"

Page 20: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Name="textBox1" VerticalAlignment="Top" Width="294" /> <ListBox Height="379" HorizontalAlignment="Right" Margin="0,12,12,0" Name="listBox1" VerticalAlignment="Top" Width="294" ItemTemplate="{DynamicResource DataTemplateItem}"/> <Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="272,406,0,0" Name=“startButton” VerticalAlignment="Top" Width="75" Click="startButton_Click" /></Grid>

Task 2 – Verification

1. Press F5 to run the application.

2. Click the Start button to begin downloading the linked pages. Note that the application is still responsive while the download executes in the background.

3. After the download completes, the application will show the list of pages with their length and title.

Page 21: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Figure 2Running the application

Exercise 3: Polling and Cancellation

In this exercise, you will add additional features to the application. First, you will introduce the ability to cancel the work that is processing in the background. Then, you will add the ability to poll the content of each of the links retrieved and check for modifications. In that case, you will notify the user by changing the link color in the ListBox.

Task 1 – Adding the Cancellation Feature

In this task, you will implement the cancellation feature in the application in order to terminate ongoing tasks.

1. Open Visual Studio 11 and load the AsyncLab-Ex3-Begin.sln solution located in the Source\[CS|VB]\Ex3-PollingAndCancellation\Begin folder of this lab. You can also continue working with the solution you’ve obtained after completing Exercise 2.

2. Open MainWindow.xaml.cs or MainWindow.xaml.vb and import the System.Threading namespace.

C#

using System.Threading;

Visual Basic

Imports System.Threading

3. Define a class variable to create the cancellation token.

(Code Snippet – Async Lab - Ex03 - Cancellation Token - CS)

C#

public partial class MainWindow : Window{ private CancellationTokenSource cancellationToken;

(Code Snippet – Async Lab - Ex03 - Cancellation Token - VB)

Visual Basic

Class MainWindow

Page 22: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Private cancellationToken As CancellationTokenSource

4. Modify the DownloadItemAsync method to receive a CancellationToken parameter.

C#

private static async Task<LinkInfo> DownloadItemAsync( Uri itemUri, CancellationToken cancellationToken){

Visual Basic

Private Shared Async Function DownloadItemAsync(ByVal itemUri As Uri, ByVal cancellationToken As CancellationToken) As Task(Of LinkInfo)

5. Create a new instance of the cancellation token inside the startButton_Click event handler.

(Code Snippet – Async Lab - Ex03 - Cancellation Token Instance - CS)

C#

private async void startButton_Click(object sender, RoutedEventArgs e){ cancellationToken = new CancellationTokenSource(); ObservableCollection<string> uris = new ObservableCollection<string>();

(Code Snippet – Async Lab - Ex03 - Cancellation Token Instance - VB)

Visual Basic

Private Async Sub startButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Start.Click

cancellationToken = New CancellationTokenSource() Dim uris As New ObservableCollection(Of String)()

6. In the startButton_Click method, modify the HttpClient call to include a cancellation token. Then, replace the GetAsync call with a SendAsync call, which supports cancellation tokens.

(Code Snippet – Async Lab - Ex03 - StartClick with CancellationToken - CS)

C#

try{ HttpRequestMessage message = new HttpRequestMessage( HttpMethod.Get, "http://msdn.microsoft.com");

Page 23: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

var response = await new HttpClient().SendAsync(message, cancellationToken.Token); string result = await response.Content.ReadAsStringAsync(); textBox1.Text = result;

(Code Snippet – Async Lab - Ex03 - StartClick with CancellationToken - VB)

Visual Basic

Try Dim message = New HttpRequestMessage(HttpMethod.Get, "http://msdn.microsoft.com") Dim response = Await (New HttpClient()).SendAsync(message, cancellationToken.Token) Dim result As String = Await response.Content.ReadAsStringAsync()

textBox1.Text = result

7. In the DownloadItemAsync method, change the HttpClient.GetAsync call with an HttpClient.SendAsync call to include a cancellation token.

(Code Snippet – Async Lab - Ex03 - DownloadItemAsync with CancellationToken - CS)

C#

try{ HttpClient httpClient = new HttpClient(); httpClient.MaxResponseContentBufferSize = 1000000;

var message = new HttpRequestMessage(HttpMethod.Get, itemUri); var response = await httpClient.SendAsync(message, cancellationToken);

item = await response.Content.ReadAsStringAsync();

(Code Snippet – Async Lab - Ex03 - DownloadItemAsync with CancellationToken - VB)

Visual Basic

Try Dim httpClient As New HttpClient httpClient.MaxResponseContentBufferSize = 1000000

Dim message = New HttpRequestMessage(HttpMethod.Get, itemUri) Dim response = Await httpClient.SendAsync(message, cancellationToken)

item = Await response.Content.ReadAsStringAsync()

Page 24: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

8. In the startButton_Click method, modify the DownloadItemAsync call in order to send the cancellation token. Replace the ListBox’s ItemsSource property assignment with the following code:

(Code Snippet – Async Lab - Ex03 - Bind ListBox To Link Info - CS)

C#

listBox1.ItemsSource = await Task.Run(() =>{ return Task.WhenAll(from uri in uris select DownloadItemAsync( new Uri(uri), cancellationToken.Token));});

(Code Snippet – Async Lab - Ex03 - Bind ListBox To Link Info - VB)

Visual Basic

listBox1.ItemsSource = Await Task.Run(Async Function() Return Await Task.WhenAll( From uri In uris Select DownloadItemAsync(New Uri(uri), cancellationToken.Token)) End Function)

9. In the startButton_Click try-catch block, add a new handler to catch the OperationCanceledException exception. Show a message box to tell the user that the operation was cancelled.

(Code Snippet – Async Lab - Ex03 - OperationCanceledException Handler - CS)

C#

}catch (OperationCanceledException){ MessageBox.Show("Operation Cancelled");}catch (Exception ex){ MessageBox.Show(ex.ToString());}

(Code Snippet – Async Lab - Ex03 - OperationCanceledException Handler - VB)

Page 25: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Visual Basic

Catch exCancel As OperationCanceledException MessageBox.Show("Operation Cancelled")Catch ex As Exception MessageBox.Show(ex.ToString())End Try

10. Open MainWindow.xaml Design View. Add a new button and set the name and the content to Cancel. If the buttons are not aligned, use the design view to place the buttons correctly in the grid. This is the XAML code of MainWindow.xaml you should obtain after the button is inserted:

XAML

<Grid> ...

<Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="231,406,0,0" Name=“startButton” VerticalAlignment="Top" Width="75" Click="startButton_Click" /> <Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="318,406,0,0" Name="cancelButton" VerticalAlignment="Top" Width="75" /> </Grid></Window>

11. Double-click the Cancel button to add an event handler.

12. In the Cancel_Click event handler, call the Cancel method from the cancellation token.

(Code Snippet – Async Lab - Ex03 - Cancel - CS)

C#

private void Cancel_Click(object sender, RoutedEventArgs e){ cancellationToken.Cancel();}

(Code Snippet – Async Lab - Ex03 - Cancel - VB)

Visual Basic

Private Sub Cancel_Click(sender As Object, e As RoutedEventArgs) Handles Cancel.Click

cancellationToken.Cancel()

Page 26: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

End Sub

13. Press F5 to run the application, and then, click the Start button.

14. Press the Cancel button. Notice you can now cancel the operation before it completes. The list on the right will only show the links that were requested before the cancellation occurred.

Figure 3Application updated with Cancel button

Task 2 – Polling the Links Status

In this task, you will add the ability to poll the links status and use different colors when their content has changed.

1. Replace all the code of LinkInfo class with the following code. You will implement INotifyPropertyChanged, taking advantage of the real time binding. Additionally, you will be adding a new property named Color. Notice that the set was implemented in all the properties to notify the changes.

Page 27: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

(Code Snippet – Async Lab - Ex03 - LinkInfo - CS)

C#

namespace AsyncLab{ using System.ComponentModel; using System.Windows.Media;

public class LinkInfo : INotifyPropertyChanged { private string html; private string title; private int length; private Color color; public event PropertyChangedEventHandler PropertyChanged; public string Title { get { return title; }

set { title = value; NotifyPropertyChanged("Title"); } }

public string Html { get { return html; }

set { html = value; NotifyPropertyChanged("Html"); } }

public int Length { get {

Page 28: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

return length; }

set { length = value; NotifyPropertyChanged("Length"); } }

public Color Color { get { return color; }

set { color = value; NotifyPropertyChanged("Color"); } }

private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }}

(Code Snippet – Async Lab - Ex03 - LinkInfo - VB)

Visual Basic

Imports System.ComponentModelImports System.Windows.Media

Public Class LinkInfo Implements INotifyPropertyChanged

Private mHtml As String Private mTitle As String Private mLength As Integer Private mColor As Color

Page 29: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) _ Implements INotifyPropertyChanged.PropertyChanged

Public Property Html() As String Get Return mHtml End Get Set(ByVal value As String) mHtml = value NotifyPropertyChanged("Html") End Set End Property

Public Property Title() As String Get Return mTitle End Get Set(ByVal value As String) mTitle = value NotifyPropertyChanged("Title") End Set End Property

Public Property Length() As Integer Get Return mLength End Get Set(ByVal value As Integer) mLength = value NotifyPropertyChanged("Length") End Set End Property

Public Property Color() As Color Get Return mColor End Get Set(ByVal value As Color) mColor = value NotifyPropertyChanged("Color") End Set End Property

Private Sub NotifyPropertyChanged(propertyName As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) End Sub

Page 30: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

End Class

2. In the MainWindow.xaml file, modify the DataTemplate resource to include a SolidColorBrush in the TextBlock.Background and bound the Color attribute to the Color property.

XAML

<Window.Resources> <DataTemplate x:Key="DataTemplateItem"> <StackPanel Orientation="Horizontal"> <TextBlock> <TextBlock.Background> <SolidColorBrush Color="{Binding Color}" /> </TextBlock.Background> <TextBlock.Text>

3. Open the MainWindow.xaml.cs or MainWindows.xaml.vb file and add the PollItem async method. It will receive an URI, a LinkInfo and a CancellationToken.

(Code Snippet – Async Lab - Ex03 - PollInfo Method - CS)

C#

private static async void PollItem( Uri itemUri, LinkInfo link, CancellationToken cancellationToken){

}

(Code Snippet – Async Lab - Ex03 - PollInfo Method - VB)

Visual Basic

Private Shared Async Sub PollItem(ByVal itemUri As Uri, ByVal link As LinkInfo, ByVal cancellationToken As CancellationToken)

End Sub

4. Implement the PollItem method to poll the URI every 5 seconds and check for changes in the content. Each time a change is found, it updates the LinkInfo by changing the color property with a random color.

(Code Snippet – Async Lab - Ex03 - PollInfo Implementation - CS)

C#

private static async void PollItem(Uri itemUri, LinkInfo link,

Page 31: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

CancellationToken cancellationToken){ Random r = new Random(); HttpClient httpClient = new HttpClient(); httpClient.MaxResponseContentBufferSize = 1000000; try { while (true) { await Task.Delay(5000, cancellationToken); var requestMessage = new HttpRequestMessage( HttpMethod.Get, itemUri); var response = await httpClient.SendAsync(requestMessage, cancellationToken); string item = await response.Content.ReadAsStringAsync();

if (item.Length != link.Length) { link.Title = GetTitle(item); link.Length = item.Length; link.Html = item; link.Color = Color.FromArgb((byte)255, (byte)r.Next(256), (byte)r.Next(256), (byte)r.Next(256)); } } } catch {

}}

(Code Snippet – Async Lab - Ex03 - PollInfo Implementation - VB)

Visual Basic

Private Shared Async Sub PollItem(ByVal itemUri As Uri, ByVal link As LinkInfo, ByVal cancellationToken As CancellationToken)

Dim r As New Random() Dim httpClient As New HttpClient httpClient.MaxResponseContentBufferSize = 1000000

Try Do

Page 32: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Await Task.Delay(5000, cancellationToken) Dim requestMessage = New HttpRequestMessage( HttpMethod.Get, itemUri) Dim response = Await httpClient.SendAsync(requestMessage, cancellationToken) Dim item As String = Await response.Content.ReadAsStringAsync() If item.Length <> link.Length Then link.Title = GetTitle(item) link.Length = item.Length link.Html = item link.Color = Color.FromArgb(Convert.ToByte(255), Convert.ToByte(r.Next(256)), Convert.ToByte(r.Next(256)), Convert.ToByte(r.Next(256))) End If Loop Catch End TryEnd Sub

Note: Task.Delay is the asynchronous version of Thread.Sleep. It returns a Task object, which completes after the specified amount of time.

5. In the DownloadItemAsync function, add a call to PollItem.

(Code Snippet – Async Lab - Ex03 - PollInfo Call - CS)

C#

public static async Task<LinkInfo> DownloadItemAsync(Uri itemUri, CancellationToken cancellationToken){ ...

LinkInfo linkInfo = new LinkInfo { Length = item.Length, Title = GetTitle(item), Html = item }; PollItem(itemUri, linkInfo, cancellationToken);

return linkInfo;}

(Code Snippet – Async Lab - Ex03 - PollInfo Call - VB)

Visual Basic

Page 33: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Private Shared Async Function DownloadItemAsync(ByVal itemUri As Uri, ByVal cancellationToken As CancellationToken) As Task(Of LinkInfo) ...

Dim linkInfo As LinkInfo = New LinkInfo() With { .Length = item.Length, .Html = item, .Title = GetTitle(item)} PollItem(itemUri, linkInfo, cancellationToken)

Return linkInfoEnd Function

6. Press F5 to run the application, and then click the Start button. Notice the background color of the list items change when the application detects an update.

Figure 4Polling links status

Page 34: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Exercise 4: Async Library Refactoring

In this exercise, you will refactor the solution in order to move the asynchronous logic to a class library, using the proper naming conventions for asynchronous methods. Additionally, you will improve the performance by avoiding the marshal of the asynchronous results back to the User Interface (UI) thread when it is not necessary.

Task 1 – Creating an Asynchronous Class Library

1. Open Visual Studio 11 and load AsyncLab-Ex4-Begin.sln solution located in the Source\[CS|VB]\Ex4-Refactoring\Begin folder of this lab. You can also continue working with the solution you’ve obtained after completing Exercise 3.

2. Create a new Class Library project into the same solution. Name the new project AsyncLabLibrary. Then, delete Class1 (created by default).

3. Add a reference to PresentationCore and System.Net.Http.

4. Copy LinkInfo class from the AsyncLab project into the AsyncLabLibrary library, and then delete the original LinkInfo file from the AsyncLab project.

5. Only for C# projects: rename the namespace in the LinkInfo.cs file from “AsyncLab” to “AsyncLabLibrary”.

6. Add a reference to the AsyncLabLibrary library in the AsyncLab project.

7. In AsyncLabLibrary project, add a new class and name it Downloader.

8. Only for C# projects: set the Downloader class access modifier to Public.

9. Include the following namespace directives:

(Code Snippet – Async Lab - Ex04 - References - CS)

C#

using System.Net.Http;using System.Text.RegularExpressions;using System.Threading;using System.Windows.Media;

(Code Snippet – Async Lab - Ex04 - References - VB)

Visual Basic

Imports System.Net.HttpImports System.Text.RegularExpressionsImports System.ThreadingImports System.Windows.Media

Page 35: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

Task 2 – Refactoring the Project

1. Open MainWindow.xaml.cs or MainWindow.xaml.vb from the AsyncLab project.

2. Move the DownloadItemAsync, PollItem and GetTitle methods from the MainWindow.xaml.cs or MainWindow.xaml.vb file to the Downloader class.

3. Rename the DownloadItemAsync method to DownloadItemAsyncInternal. If you are working in C#, use Visual Studio Refactoring to rename any reference to the method.

4. Rename the PollItem method to PollItemAsync.If you are working in C#, use Visual Studio Refactoring feature to rename any reference to the method. Otherwise, rename the PollItem method call to PollItemAsync in the DownloadItemAsync method.

5. Create a DownloadItemAsync public method. The method will receive an URI and a CancellationToken to support cancellation and call DownloadItemAsyncInternal.

(Code Snippet – Async Lab - Ex04 - DownloadItemAsync - CS)

C#

public static Task<LinkInfo> DownloadItemAsync(Uri itemUri, CancellationToken cancellationToken){ if (itemUri == null) { throw new ArgumentNullException("itemUri"); }

return DownloadItemAsyncInternal(itemUri, cancellationToken);}

(Code Snippet – Async Lab - Ex04 - DownloadItemAsync - VB)

Visual Basic

Public Shared Function DownloadItemAsync(ByVal itemUri As Uri, ByVal cancellationToken As CancellationToken) As Task(Of LinkInfo)

If itemUri Is Nothing Then Throw New ArgumentNullException("itemUri") End If

Return DownloadItemAsyncInternal(itemUri, cancellationToken)End Function

6. Create an overload method for DownloadItemAsync without the cancellation token parameter.

Page 36: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

(Code Snippet – Async Lab - Ex04 - DownloadItemAsync No Cancellation - CS)

C#

public static Task<LinkInfo> DownloadItemAsync(Uri itemUri){ return DownloadItemAsync(itemUri, CancellationToken.None);}

(Code Snippet – Async Lab - Ex04 - DownloadItemAsync No Cancellation - VB)

Visual Basic

Public Shared Function DownloadItemAsync( ByVal itemUri As Uri) As Task(Of LinkInfo)

Return DownloadItemAsync(itemUri, CancellationToken.None)End Function

7. Modify the DownloadItemAsyncInternal method to call the ConfigureAwait method at the end of SendAsync call, and set its parameter to false. To do that, replace the line that performs a GetAsync call with the following code:

(Code Snippet – Async Lab - Ex04 - DownloadItemAsyncInternal ConfigureAwait- CS)

C#

var message = new HttpRequestMessage(HttpMethod.Get, itemUri);var response = await httpClient.SendAsync( message, cancellationToken).ConfigureAwait(false);

(Code Snippet – Async Lab - Ex04 - DownloadItemAsyncInternal ConfigureAwait - VB)

Visual Basic

Dim message = New HttpRequestMessage(HttpMethod.Get, itemUri)Dim response = Await httpClient.SendAsync( message, cancellationToken).ConfigureAwait(False)

Note: When a call that uses the await keyword completes, it marshals the continuation (the remainder of the method’s execution) back to the UI thread. If this is not needed, call ConfigureAwait(false) for improved performance.

8. Modify the PollItemAsync method to call ConfigureAwait at the end of the SendAsync call, and set its parameter to false.

Page 37: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

(Code Snippet – Async Lab - Ex04 - PollItem ConfigureAwait- CS)

C#

await Task.Delay(5000, cancellationToken);var requestMessage = new HttpRequestMessage( HttpMethod.Get, itemUri);var response = await httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);

(Code Snippet – Async Lab - Ex04 - PollItem ConfigureAwait - VB)

Visual Basic

Await Task.Delay(5000, cancellationToken)Dim requestMessage = New HttpRequestMessage(HttpMethod.Get, itemUri)Dim response = Await httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(False)

9. Open MainWindow.xaml.cs or MainWindow.xaml.vb code-behind file and import the AsyncLabLibrary namespace.

(Code Snippet – Async Lab - Ex04 - References dll - CS)

C#

using AsyncLabLibrary;

(Code Snippet – Async Lab - Ex04 - References dll - VB)

Visual Basic

Imports AsyncLabLibrary

10. In the startButton_Click method, replace the ListBox polling code to call the new DownloadItemAsync method from the downloader library.

(Code Snippet – Async Lab - Ex04 - DownloadItemAsync Call - CS)

C#

listBox1.ItemsSource = await Task.Run(() =>{ return Task.WhenAll(from uri in uris select Downloader.DownloadItemAsync(new Uri(uri), cancellationToken.Token));});

Page 38: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

(Code Snippet – Async Lab - Ex04 - DownloadItemAsync Call - VB)

Visual Basic

listBox1.ItemsSource = Await Task.Run(Async Function() Return Await Task.WhenAll( _ From uri In uris _ Select Downloader.DownloadItemAsync( New Uri(uri), cancellationToken.Token)) End Function)

11. Press F5 to run the application. You will notice no difference from the client side. The application UI is responsive, even while the links are being downloaded and polled. ConfigureAsync provides a performance improvement, as it does not wait for the data to be marshaled back to the UI thread.

Appendix: Using Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them, as shown in the following figure.

Figure 5Using Visual Studio code snippets to insert code into your project

Page 39: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

To add a code snippet using the keyboard (C# only)

1. Place the cursor where you would like to insert the code.

2. Start typing the snippet name (without spaces or hyphens).

3. Watch as IntelliSense displays matching snippets' names.

4. Select the correct snippet (or keep typing until the entire snippet's name is selected).

5. Press the Tab key twice to insert the snippet at the cursor location.

Figure 6Start typing the snippet name

Figure 7Press Tab to select the highlighted snippet

Figure 8Press Tab again and the snippet will expand

To add a code snippet using the mouse (C#, Visual Basic and XML)

1. Right-click where you want to insert the code snippet.

2. Select Insert Snippet followed by My Code Snippets.

Page 40: Asynchronous Programming in the .NET Framework 4.5az12722.vo.msecnd.net/.../labs/asyncnet451-1-0-0/Lab.docx · Web viewMicrosoft .NET Framework 4.5 introduces new language features

3. Pick the relevant snippet from the list, by clicking on it.

Figure 9Right-click where you want to insert the code snippet and select Insert Snippet

Figure 10Pick the relevant snippet from the list, by clicking on it