0% found this document useful (0 votes)
51 views25 pages

Asynchronous Programming

Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No part of this document may be reproduced, stored in or introduced into a retrieval system, or for any purpose, without the express written permission of Microsoft Corporation. After completing this module, students will be able to:.. Use the techniques of Asynchronous Programming and multithreading to avoid blocking the user

Uploaded by

satheeshbkumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views25 pages

Asynchronous Programming

Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No part of this document may be reproduced, stored in or introduced into a retrieval system, or for any purpose, without the express written permission of Microsoft Corporation. After completing this module, students will be able to:.. Use the techniques of Asynchronous Programming and multithreading to avoid blocking the user

Uploaded by

satheeshbkumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 25

Information in this document, including URL and other Internet Web site references, is subject to change without notice.

Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express

Module 7: Asynchronous Programming


written permission of Microsoft Corporation.

Contents Overview Lesson: The .NET Asynchronous Programming Model Lesson: The Asynchronous Programming Model Design Pattern Lesson: How to Make Asynchronous Calls to Any Method Lesson: Protecting State and Data in a Multithreaded Environment Review Lab 7.1: Making Asynchronous Calls to an XML Web Service 1 2 7 19 27 34 36

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Active X, Authenticode, FrontPage, IntelliSense, MSDN, PowerPoint, Visual Basic, Visual C#, Visual Studio, Win32, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Module 7: Asynchronous Programming

Instructor Notes
Presentation: 90 minutes Lab: 45 minutes In this module, students learn how to use the techniques of asynchronous programming and multithreading to avoid blocking the user interface of an application. After completing this module, students will be able to:

Describe the Microsoft .NET Framework asynchronous programming model. Modify a client application to use built-in .NET Framework support for asynchronous calls to methods. Describe how to add explicit support for asynchronous calls to any method.

Required materials Preparation tasks

To teach this module, you need the Microsoft PowerPoint file 2555A_07.ppt. To prepare for this module:

Read all of the materials for this module. Review the animation for this module. Complete the demonstrations, practice, and lab.

How to Teach This Module


This section contains information that will help you to teach this module.

If students are interested in referencing code examples in other languages, point them to Language Equivalents in Microsoft Visual Studio .NET Help documentation. This section provides examples in languages such as Microsoft Visual Basic .NET, C#, and Java. The lab at the end of this module is based on the Expense Report application in Course 2555A, Developing Microsoft .NET Applications for Windows (Visual C# .NET), and is intended to simulate a real-world environment in which students will demonstrate what they learned during the lecture and practice portions of the module. The lab does not provide step-by-step detailed instructions; instead, the students are given tasks to complete in the left column and a list of resources that they can use (if they need help) in the right column. Students get hands-on experience that they need by completing the practice activity in the module.

Lesson: The .NET Asynchronous Programming Model


This section describes the instructional methods for teaching this lesson. This is a brief overview lesson to define asynchronous programming and provide scenarios in which it is appropriate to use asynchronous programming. Wait to discuss implementation until you teach the next lesson.

Module 7: Asynchronous Programming

iii

Lesson: The Asynchronous Programming Model Design Pattern


This section describes the instructional methods for teaching this lesson. Emphasize to students that when they use .NET Framework classes that include support for asynchronous programming they do not have to implement the BeginOperation and EndOperation methods. These are provided by the .NET Framework, and all they, as developers, must do is to call these methods. Overview of the Asynchronous Programming Model Design Pattern Focus on the asynchronous callback technique for completion, because this is the technique that is used in the rest of the lesson and is the most typical technique to use for Windows Forms applications.

Lesson: How to Make Asynchronous Calls to Any Method


This section describes the instructional methods for teaching this lesson. Point out to students that even when they create and use a delegate to call any method, the .NET Framework still provides the implementation of the BeginInvoke and EndInvoke methods.

Lesson: Protecting State and Data in a Multithreaded Environment


This section describes the instructional methods for teaching this lesson. Tell students that especially for Windows Forms application, they should be able to design the application to minimize the need for synchronization. They can accomplish this by selectively enabling and disabling user interface elements as asynchronous operations are performed.

Module 7: Asynchronous Programming

Overview
Introduction A well-designed Microsoft .NET Framework Windows Forms application includes techniques to prevent blocking user interaction. In this module, you will learn how to use the techniques of asynchronous programming and multithreading to avoid blocking the user interface of an application. Objectives After completing this module, you will be able to:

Describe the .NET Framework asynchronous programming model. Modify a client application to use built-in .NET Framework support for asynchronous calls to methods. Describe how to add explicit support for asynchronous calls to any method.

Lesson: The .NET Asynchronous Programming Model


Introduction The .NET Framework provides extensive support for asynchronous calls and multithreading. In this lesson, you will learn about asynchronous programming and. the NET asynchronous programming model. Lesson objectives After completing this lesson, you will be able to:

Define asynchronous programming. List typical scenarios in which asynchronous programming is useful. Describe the .NET asynchronous programming model.

What Is Asynchronous Programming?


Introduction One important measure of a Windows Forms application is its timely response to user interaction. One important technique developers have to support responsiveness is asynchronous programming. The central idea behind asynchronous programming is to be able to issue method calls to other components and to carry on with other work, without waiting for the operation to complete. The .NET Framework common language runtime provides rich support for asynchronous programming and handles the details of threading and data exchange.

Definition

Module 7: Asynchronous Programming

Example of asynchronous scenarios

In a non-programming scenario, consider a painting crew that is painting the rooms in a house that is some distance from town. As they are painting walls of the rooms, the crew chief realizes that they did not bring enough trim paint for the woodwork. The crew chief can tell one of the crew members to go to the paint store to order and wait for more trim paint to be custom mixed to the appropriate color, while the rest of the crew continues to paint the walls. When the crew member finally returns with the trim paint, some members of the crew can switch to painting the woodwork in those rooms where the walls have dried. There are quite a few scenarios in the programming world that involve potential wait times: requests for file or network input/output (I/O), Web access, and so forth. You can use asynchronous techniques in your applications in these scenarios to allow users to remain productive.

Demonstration: Comparing Synchronous and Asynchronous Versions of an Application


Introduction Instructions In this demonstration, you see a comparison of the user experience in synchronous and asynchronous versions of the Expense Report application.

To demonstrate the synchronous behavior of the Expense Report


application .1 Run the synchronous version of the Expense Report application, ExpenseReport.exe, in install_folder\Democode\Mod07\Mod07_01\Sync. Note If you performed a default installation of the course files, install_folder corresponds to C:\Program Files\Msdntrain\2555. .2 In the main application window, click the View Submitted Reports button. .3 Notice that the application is not responsive while the XML Web service is being called. You can test this by trying to move the main application window, or by trying to minimize the main application window before the expense report list window opens. .4 After the expense report list window opens, close the application.

To demonstrate the asynchronous behavior of the Expense Report


application .1 Run the asynchronous version of the Expense Report application, ExpenseReport.exe, in install_folder\Democode\Mod07\Mod07_01\Async. .2 On the main application window, click the View Submitted Reports button.

Module 7: Asynchronous Programming

.3 Notice that the application is responsive while the XML Web service is being called. You can test this by moving the splitter control in the expense report list window, or by minimizing the main application window. .4 After data is loaded in the expense report list window, close the application.

Asynchronous Programming Support in the .NET Framework


Introduction The .NET Framework provides a design pattern for asynchronous programming and built-in support for many areas which often involve making complex calls that take a considerable amount of time to complete. The .NET Framework provides a design pattern that makes asynchronous calls uniform across the different parts of the .NET Framework. Classes that include built-in support have a pair of asynchronous methods for each synchronous method they contain. For example, if you want to read from a stream synchronously, you use the Read method of the System.IO.Stream class. If, however, you want to make the call asynchronously, then you would instead use the BeginRead and EndRead methods of the System.IO.Stream class. In addition, the .NET Framework makes the details of threading that support asynchronous programming mechanisms largely transparent to the developer. For more information about using the support provided for asynchronous programming by the .NET Framework in your applications, see the lesson The Asynchronous Programming Model Design Pattern in this module.

Support provided by the .NET Framework

Lesson: The Asynchronous Programming Model Design Pattern


Introduction The asynchronous programming model design pattern provides a consistent and type-safe way to call methods asynchronously. This lesson concentrates on how to make asynchronous calls to classes that contain built-in asynchronous support. In the lesson How to Make Asynchronous Calls to Any Method, you will learn about the additional steps you must take to make asynchronous calls to classes that do not contain built-in asynchronous support. After completing this lesson, you will be able to:

Lesson objectives

Describe the asynchronous programming model design pattern. List the four ways to be notified of completion and describe appropriate scenarios for each way. List the steps for using asynchronous callback as the notification method.

Module 7: Asynchronous Programming

Modify a client application to use built-in .NET Framework support for asynchronous calls to methods.

Overview of the Asynchronous Programming Model Design Pattern


Introduction Beginning the operation One of the innovations provided by the asynchronous design pattern is that the caller can decide whether a particular call should be asynchronous. After you determine that you want to make an asynchronous call to one of the classes that provides built-in asynchronous support, you simply make a call to the classs appropriate BeginOperation method and determine what method you want to use to complete the call. The call to BeginOperation returns an object implementing this IAsyncResult interface. Depending on the completion technique used, this object may be used to help complete or get information about the asynchronous operation. You must also determine how you want your application to be notified of the completion of the asynchronous call and to receive the results (if any) of the call. When you want to avoid blocking the thread that made the asynchronous call, use a callback method to be notified of the asynchronous call completion. This is the technique most appropriate when you want to avoid blocking user interaction, for example in Windows Forms applications, or in other heavily event-driven processing scenarios. For this reason the remainder of this lesson will focus on using this technique. When you use a callback, you typically call the EndOperation method, described later in this topic, inside the callback method to retrieve the results of the asynchronous operation. Polling If you want to maintain complete control over the flow of the application, then you can use a polling method. When using this technique, you will incur the overhead of manually checking the returned IAsyncResult interfaces IsCompleted property to determine if the call is completed. This technique is typically not appropriate for event-driven or user interaction scenarios. EndOperation The EndOperation technique can be used when you have a finite amount of work to be done on the main thread that is not dependent on the asynchronous call. After that work is done and your application must receive the results of the asynchronous operation before it can do any further meaningful work, you can call the EndOperation method to block until the asynchronous operation completes. Be aware that an EndOperation might block forever if the asynchronous call never completes due to a network or server failure. Therefore, the wait on a handle technique might be more appropriate to use in certain situations.

Receiving completion notification and results Callback

Module 7: Asynchronous Programming

Wait on a handle

With the wait on a handle technique, you can specify a maximum time-out to wait for an asynchronous operation to complete. You can also use the System.Threading.WaitHandle.WaitAll method to wait on multiple asynchronous operations and be notified when they have all completed. For more information about using the polling and wait on a handle techniques, see Module 14, Threading and Asynchronous Programming in Course 2349B, Programming with the Microsoft .NET Framework (Microsoft Visual C# .NET).

Using the Design Pattern with an Asynchronous Callback for Completion


Introduction Before providing the details of the code used for making an asynchronous call with an asynchronous callback for completion, it is useful to provide an overview of the process. When you use the callback as the completion technique, there are four main steps in the process: .1 To set up for the asynchronous call, create an asynchronous delegate that points to the callback method you want to have invoked when the asynchronous operation completes. A delegate is an object that you can use to call the methods of other objects. In other words, a delegate is an object-oriented, type-safe, secure way to provide the functionality of a function pointer in the .NET Framework. .2 Wherever appropriate in your application, initiate the asynchronous call by invoking the appropriate BeginOperation method, passing it the asynchronous delegate. .3 Inside the callback, invoke the appropriate EndOperation method to retrieve results, if appropriate. .4 Return control to the main thread to update the user interface. The remaining topics in this lesson provide the programming details related to these steps.

Process: Using asynchronous callbacks for completion

Definition

How to Set Up and Initiate the Call


Introduction An appropriate scenario for using a callback to notify completion and return results of an asynchronous call is calling a method of an XML Web service to obtain information for a Windows Forms application. .1 Set up the asynchronous call by creating an asynchronous delegate that points to the callback method that you want to have invoked when the

Procedure: Setting up and initiating the call

Module 7: Asynchronous Programming

asynchronous operation completes, in this case the AsyncCB method of the form from which you make the call.
AsyncCallback delCB = new AsyncCallback( this.AsyncCB);

Notice that part of the .NET Framework support provided for asynchronous programming is the AsyncCallback delegate class. The signature for a method referred to by an AsyncCallback delegate is as follows.
void AsyncCB (IAsyncResult ar);

For more information about the AsyncCallback delegate, search for AsyncCallback delegate in the Microsoft Visual Studio .NET Help documentation. .2 Initiate the asynchronous call by invoking the BeginOperation method, in this case WS.BeginGetReportsForEmployee, and passing it the callback delegate, in this case, delCB. Notice that the callback delegate is always passed in as the next to the last parameter.
WS.BeginGetReportsForEmployee( username, pwdToken, RecordCursor, 10, TotalNumRecords, delCB, null);

The final parameter of the BeginInvoke method is of type System.Object and is for user data. This user data is passed into the callback when the operation is completed in the AsyncState property of the IAsyncResult parameter of the callback. The .NET Framework will take care of allocating a thread from the thread pool to run the code in the GetReportsForEmployee method and, when it completes, will call the method pointed to by delCB (AsyncCB).

How to Receive Completion Notification and Results


Introduction Procedure: Receiving completion notification and results After the method that you called asynchronously has completed its work, the .NET Framework calls the asynchronous callback delegate that you designated. Inside the asynchronous callback delegate, call the appropriate EndOperation method and return any results.
// Inside the callback method, AsyncCB, call // EndOperation to get the results of the async call void AsyncCB (IAsyncResult ar) { ... ExpRepDataSet = WS.EndGetReportsForEmployee( ar, out TotalNumRecords); ... }

Module 7: Asynchronous Programming

Exceptions

If the asynchronous operation throws an exception, it will be returned from the call to the EndOperation method.

How to Return Control to the Main Thread


Introduction In Windows Forms applications, any changes to properties for controls on forms must be done on the main thread. Methods and properties for controls cannot be safely accessed from any other thread. To return control to the main thread: .1 From inside the callback, switch back to the main thread.
//Switch back to main thread to update UI //First, create a MethodInvoker delegate for //the method to be called MethodInvoker mi = new MethodInvoker( this.UpdateUI);

Procedure: Returning control to the main thread

The .NET Framework provides a MethodInvoker delegate class that you can use to call generic methods. In the previous code sample, you create a delegate that refers to the UpdateUI method in the current object. The signature for a method referred to by a MethodInvoker delegate is as follows.
void UpdateUI();

.2 Update the user interface.


//Use the current forms BeginInvoke to //invoke the delegate. this.BeginInvoke(mi);

This call to the forms BeginInvoke method will cause the method referred to by mi to be called on the main thread and therefore update the user interface (UI) safely. By calling the BeginInvoke method instead of the Invoke method, the worker thread used to make the asynchronous call returns to the thread pool faster, thus avoiding exhaustion of threads in the thread pool.

Animation: Making an Asynchronous Call to an XML Web Service


In this animation, you will see how an object makes an asynchronous call to an XML Web service.

Module 7: Asynchronous Programming

A Microsoft Windows Forms client application calls an XML Web service to retrieve and change information about expense reports. The XML Web service provides a SubmitReport method that takes an expense report, validates it, and adds it to the database of expense reports. When a Web service reference is added to a Microsoft Visual Studio .NET project, a client proxy class for the XML Web service is generated. In addition to the synchronous SubmitReport method, the proxy includes the asynchronous BeginSubmitReport and EndSubmitReport methods. A callback method named SubmitReportCallback is used as the callback method for the asynchronous operation. The asynchronous operation is started by calling the proxys BeignSubmitReport method, passing a delegate object that refers to the callback method. When the BeginSubmitReport method is called, it calls the SubmitReport method on another thread from the runtimes thread pool and returns immediately to the caller. The client is free to continue executing other code and the user interface remains responsive. When the SubmitReport method completes, the callback method is invoked. The callback method invokes the EndSubmitReport method to retrieve the results of the XML Web service call. If the SubmitReport method completed successfully, the EndSubmitReport method returns the results; otherwise, an exception is thrown in the EndSubmitReport method for the callback to handle. The application displays the results of the XML Web service call by using the UpdateUI method. The UpdateUI method manipulates controls to show the results. Controls can only be called safely from the applications main thread. The callback method is not executing on the applications main thread, and therefore cannot call the UpdateUI method directly. Instead, it calls the forms thread-safe BeginInvoke method, passing it a delegate to the UpdateUI method. BeginInvoke then executes this method on the main thread.

Practice: Making an Asynchronous Call to an XML Web Service


Introduction Instructions In this practice, you will convert a synchronous XML Web service call to an asynchronous XML Web service call.

Observe the synchronous version of the Expense Report application


.1 Open the Mod07Practice.sln solution file in install_folder\Practices\Mod07\Mod07_01\Starter. .2 Open the MainForm.cs file and view the code. .3 Build the project and run the application. .4 Click Call Web Service. While the XML Web service call is happening, click the minimize button to try to minimize the application. Notice that the application is not responsive. It will not minimize until the XML Web service call completes.

Module 7: Asynchronous Programming

.5 Click Exit to quit the application.

Modify the Expense Report application to make asynchronous calls


.1 Show TODO comments in the Task List. To show TODO comments, on the View menu, point to Show Tasks, and then click All. .2 Find the first TODO comment in the code. Add the code to instantiate an AsyncCallback delegate that refers to the WebserviceCallback method of this class.
AsyncCallback asyncCB = new AsyncCallback( this.WebserviceCallback);

.3 Find the next TODO comment. Add the code to begin the call to the XML Web service.
WS.BeginGetReportsForEmployee(null, null, 0, 10, TotalReports, asyncCB, null);

.4 Find the next TODO comment and uncomment the line of code below the TODO comment. .5 Find the next two TODO comments. Comment out the rest of the code (the synchronous code) in the method. .6 Find the next TODO comment. Add the code to finish the call to the XML Web service.
ExpenseReports = WS.EndGetReportsForEmployee(result, out TotalReports);

.7 Find the next TODO comment. Add the code to instantiate a MethodInvoker delegate that points to the UpdateUI method of this class.
MethodInvoker mi = new MethodInvoker(this.UpdateUI);

.8 Find the next TODO comment. Add the code to call BeginInvoke on this form, passing the MethodInvoker delegate created in step 6.
this.BeginInvoke(mi);

.9 Save your files and build the project.

Observe how the Expense Report application behavior has changed


.1 Run the application. .2 Click Call Web Service. After the message Async: Calling web service... appears, try to minimize the window. Notice that the UI is still responsive during the call to the XML Web service. .3 Click Exit to quit the application. .4 Set breakpoints in the CallBtn_Click, WebserviceCallback, and UpdateUI methods. Rerun the application to see the flow of control of the asynchronous operation.

Lesson: How to Make Asynchronous Calls to Any Method

Module 7: Asynchronous Programming

Introduction

It is not necessary for a called object to provide explicit support for asynchronous calls. The .NET Framework provides services required for you to call any method asynchronously. After completing this lesson, you will be able to:

Lesson objectives

Describe how to make asynchronous calls to any method. Explicitly create and call asynchronous delegates.

Overview of How to Make Asynchronous Calls to Any Method


Introduction When you make asynchronous calls to classes that contain built-in support for asynchronous programming, such as XML Web services and stream I/O, the compiler creates asynchronous delegates and their BeginOperation and EndOperation methods for you. When you want to asynchronously call methods in classes without built-in support, you must explicitly create and call the delegate for the method that you want to invoke. A delegate is an object-oriented, type-safe, secure way to provide the functionality of a function pointer in the .NET Framework. Asynchronous delegates allow you to call a synchronous method in an asynchronous manner. After creating the asynchronous delegate, you then follow the same process that you would use for making asynchronous calls to classes with built-in support: .1 Choose the completion mechanism that you want to use and do any setup the completion mechanism requires. .2 Initiate the asynchronous call. .3 Receive the completion notification and any results. .4 Return control to the main thread and update the UI, as appropriate. Techniques for protecting state and data is covered in the topic How to Protect State and Data in a Multithreaded Environment in this module.

Explicitly create the asynchronous delegate Definition

Follow design pattern for asynchronous programming

How to Create the Asynchronous Delegate


Introduction After you have explicitly declared an asynchronous delegate, you can use the asynchronous methods of a delegate object created for you by the compiler. The .NET Framework will still make the threading infrastructure necessary for asynchronous programming transparent to you.

Module 7: Asynchronous Programming

11

Procedure: Declaring the delegate

To declare the delegate, use the delegate keyword.


public delegate int CalcDelegate( int startingValue, int interestRate);

The previous code declares a delegate to a method that returns an integer and takes two integers as parameters. Because Microsoft Visual C# and Microsoft Visual Basic .NET compilers support asynchronous delegates, they generate the Invoke method and the BeginInvoke and EndInvoke methods when you declare the delegate. Use the Invoke method if you want to call the target method synchronously. Use the BeginInvoke method to call the target method asynchronously. The runtime queues the request and returns immediately to the caller. The target method will be called on a thread from the thread pool. The original thread that submitted the request is free to continue executing in parallel to the target method, which is running on a thread pool thread. If a callback has been specified on BeginInvoke, it is called when the target method returns. In the callback, the EndInvoke method is used to obtain the return value and the in/out parameters. If the callback is not specified on BeginInvoke, you can use the other asynchronous design pattern techniques, for example, polling, on the original thread that submitted a request. Procedure: Instantiating the delegate Instantiate the class that contains the method that the delegate will point to.
TotalReturnCalc tr = new TotalReturnCalc();

Then instantiate the delegate, passing in the method it points to.


CalcDelegate cd = new CalcDelegate(tr.CalculateReturn);

How to Initiate the Asynchronous Call


Introduction Using a callback method as the completion mechanism is most appropriate for Windows Forms applications. To use the callback method, you must create a delegate to safely invoke it. To create the delegate that allows you to call the callback method, instantiate an AsyncCallback object:
AsyncCallback cb = new AsyncCallback(this.ResultsCB);

Procedure: Creating the delegate to the callback method

In the code example above, this refers to the object from which you are making the asynchronous call. Alternatively, the method that handles the callback could be in a different object, if necessary for your scenario. Procedure: Calling the BeginInvokemet hod To call the BeginInvoke method, pass the callback delegate, named cb in the code example, to the BeginInvoke method as the second to last parameter.

Module 7: Asynchronous Programming


IAsyncResult ar = cd.BeginInvoke(startVal, intRate, cb, null);

The final parameter of the BeginInvoke method is of type System.Object and is for user data. This user data is passed into the callback when the operation is completed in the AsyncState property of the IAsyncResult parameter of the callback.

How to Complete the Asynchronous Call


Introduction When the asynchronous operation completes, the .NET Framework calls your callback method. Your callback method, in turn, calls the EndInvoke method to notify the caller of completion. For Windows Forms applications, you must return control to the main thread before updating the user interface. You can call the EndInvoke method to retrieve the results of the operation.
int result = cd.EndInvoke(ar);

Procedure: Calling the EndInvoke method Exceptions Updating the UI

If the asynchronous operation throws an exception, it will be returned from the call to the EndInvoke method. In Windows Forms applications, you must return control to the main thread before updating the user interface.

How to Return Control to the Main Thread and Update the UI


Introduction Procedure: Instantiating a MethodInvoker delegate Procedure: Invoking the MethodInvoker delegate asynchronously As with the design pattern discussed in the previous lesson, you use the MethodInvoker delegate to transfer control to the main thread.
MethodInvoker mi = new MethodInvoker(this.UpdateUI);

this.BeginInvoke(mi);

By calling the UpdateUI method asynchronously, by using BeginInvoke instead of Invoke, the worker thread used to make the asynchronous call returns to the thread pool faster, thus promoting better application performance. Notice that this step is necessary only if the UI in a Windows Forms application must be updated. Also notice that all of the steps after creating the delegate are the same in this case as they are in the case in which a delegate is not used.

Module 7: Asynchronous Programming

13

Demonstration: Using Asynchronous Delegates


Introduction In this demonstration, you will see how to call a method asynchronously from a Windows Forms application.

To view the code for the application


.1 Open the AsyncDelegates.sln solution file in install_folder\Democode\Mod07\Mod07_02\AsyncDelegates. .2 Open the Class1.cs source file and view the code. .3 Notice the FactorizeDelegate declaration near the top of the file. This shows an example of a delegate declaration. .4 Notice the Factorize method in the PrimeFactorizer class. This is the method the delegate will refer to and invoke asynchronously. .5 Notice the FactorizeNumber method in the Simple class. This is the method that instantiates a PrimeFactorizer object, then instantiates a delegate referring to the Factorize method in that class. Then it calls BeginInvoke on the delegate. .6 Notice the FactorizedResults method in the Simple class. This is the callback method that is invoked when the asynchronous operation completes.

To view the flow of control as the application executes


.1 Set breakpoints at the top of the Factorize, FactorizeNumber, and FactorizedResults methods. .2 Run the application, noticing the flow of control between the three methods mentioned above.

Lesson: Protecting State and Data in a Multithreaded Environment


Introduction No synchronization is the default for objects. Therefore, when you use asynchronous programming techniques, you must consider how to protect state and data in this multithreaded environment. After completing this lesson, you will be able to describe techniques to protect state and data in a multithreaded environment.

Lesson objective

How to Protect State and Data in a Multithreaded Environment

Module 7: Asynchronous Programming

Introduction

For many Windows Forms applications, little state protection code may be necessary, because most access of object state happens on the main thread. However, this will not be the case for every application. The System.Threading namespace provides classes and interfaces for synchronizing access to data to provide thread safety. You can use the SynchronizationAttribute on any class that is derived from ContextBoundObject to synchronize all instance methods and fields. All objects in the same context domain share the same lock. Multiple threads are allowed to access the instance methods and fields, but only a single thread is allowed at any one time. Static members are not protected from concurrent access by multiple threads. Note Using automatic synchronization can incur more overhead than using manual synchronization techniques.

Automatic synchronization

Synchronized code regions

Another technique that you can use is a compiler keyword to synchronize blocks of code, instance methods, and static methods. In Visual C#, the keyword is lock. This keyword uses the Monitor class to lock the object. When you use the lock keyword, the compiler generates code. The Visual C# compiler emits a try/finally block with Monitor.Enter at the beginning of the try, and Monitor.Exit in the finally block. If an exception is thrown inside of the lock block, the finally handler runs to allow you to perform any clean-up work. The C# statement, of the form lock(x) where x is an expression of a referencetype, is equivalent to the following except that x is evaluated only once:
System.Threading.Monitor.Enter(x); try { ... } finally { System.Threading.Monitor.Exit(x); }

The lock keyword marks a statement block as a critical section. lock(expression) statement_block, where expression specifies the object that you want to lock on. expression must be a reference type. Typically, expression is this if you want to protect an instance variable, or typeof(class) if you want to protect a static variable or if the critical section occurs in a static method in the specified class. The statement_block includes the statements of the critical section. For example, to synchronize access in a static method:

Module 7: Asynchronous Programming


using System; using System.Threading; class Cache { public static void Add(object x) { // method code that doesn't require exclusive access lock (typeof(Cache)) { // code requiring exclusive access to static data } // method code that doesn't require exclusive access } }

15

Or, to synchronize access in an instance method:


class Counter { public override int Read(int threadNum) { // ... // method code that doesn't require exclusive access lock(this) { // code requiring exclusive access to instance data } // method code that doesn't require exclusive access } }

Manual synchronization

You can use the Monitor, Interlocked, Mutex, ManualResetEvent, AutoResetEvent, and ReaderWriterLock classes to acquire and release a lock to protect global, static, and instance fields and global, static, and instance methods. For many UI-based applications, little or no special synchronization code is required. All of the changes of the UI must happen on the main application thread, so this usually forces synchronous access to state information. Also, careful enabling and disabling of UI elements can prevent the application from getting into an undefined state. For example, the Expense Reporting sample application enables and disables buttons as asynchronous XML Web service calls are made to prevent threading-related problems. Therefore, no special synchronization code is required in the Expense Reporting application, other than the use of MethodInvoker delegates to switch control to the main thread upon completion of asynchronous calls. For more information about synchronization techniques, see Module 14, Threading and Asynchronous Programming in Course 2349B, Programming with the Microsoft .NET Framework (Microsoft Visual C# .NET).

Designing applications to minimize synchronization needs

Module 7: Asynchronous Programming

Demonstration: Protecting State and Data in a Multithreaded Environment


Introduction In this demonstration, you will see how to protect state and data by using a synchronized code region.

To view the code for the ThreadSafety application


.1 Open the ThreadSafety.sln solution file in install_folder\Democode\Mod07 \Mod07_03\ThreadSafety. .2 Open the Class1.cs source file and view the code. .3 Notice the Read method in the CounterUnsafe class. This method reads the count member variable twice, with a delay in between the two readings. If other threads change the value of count during that interval, two different values will be read. .4 Notice the Increment method in the CounterUnsafe class. This method increments the count variable, with a long delay between when it reads the value of count and writes the updated value of count. If other threads try to update the value of count during this interval, the value of count written by this method overwrites the results of other calls. .5 Notice the Read method in the CounterUsingLock class. This method reads the count variable twice, with a delay in between the two readings. However, this method accesses count in a lock code block, so the value of count will not change between the two readings. .6 Notice the Increment method in the CounterUsingLock class. This method increments the count variable, with a long delay between when it reads the value of count and writes the updated value of count. However, this method accesses count in a lock code block, so the value of count cannot be changed while this method accesses it.

To run the application and view the output


.1 To open the Visual Studio .NET command prompt, click Start, point to All Programs, point to Microsoft Visual Studio .NET, point to Visual Studio .NET Tools, and then click Visual Studio .NET Command Prompt. .2 Change directories to install_folder\Democode\Mod07\ Mod07_03\ThreadSafety\bin\debug. Run the application ThreadSafety.exe from the command line. .3 View the output of the test. The output should look similar to the following.

Module 7: Asynchronous Programming


Unsafe test: Start Resource writing (Thread=0) count: 0 Stop Resource writing (Thread=0) count: 1 Start Resource reading (Thread=1)count: 1 Stop Resource reading (Thread=1) count: 1 Start Resource writing (Thread=2) count: 1 Stop Resource writing (Thread=2) count: 2 Start Resource reading (Thread=3)count: 2 Stop Resource reading (Thread=3) count: 2 Start Resource writing (Thread=4) count: 2 Stop Resource writing (Thread=4) count: 3 Start Resource reading (Thread=5)count: 3 Start Resource writing (Thread=6) count: 3 Stop Resource reading (Thread=5) count: 3 Start Resource reading (Thread=7)count: 3 Stop Resource reading (Thread=7) count: 3 Start Resource writing (Thread=8) count: 3 Stop Resource writing (Thread=6) count: 4 Start Resource reading (Thread=9)count: 4 Stop Resource reading (Thread=9) count: 4 Stop Resource writing (Thread=8) count: 4 All Unsafe threads have completed. Lock test: Start Resource writing (Thread=0) count: 0 Stop Resource writing (Thread=0) count: 1 Start Resource reading (Thread=1)count: 1 Stop Resource reading (Thread=1) count: 1 Start Resource writing (Thread=2) count: 1 Stop Resource writing (Thread=2) count: 2 Start Resource reading (Thread=3)count: 2 Stop Resource reading (Thread=3) count: 2 Start Resource writing (Thread=4) count: 2 Stop Resource writing (Thread=4) count: 3 Start Resource reading (Thread=5)count: 3 Stop Resource reading (Thread=5) count: 3 Start Resource writing (Thread=6) count: 3 Stop Resource writing (Thread=6) count: 4 Start Resource reading (Thread=7)count: 4 Stop Resource reading (Thread=7) count: 4 Start Resource writing (Thread=8) count: 4 Stop Resource writing (Thread=8) count: 5 Start Resource reading (Thread=9)count: 5 Stop Resource reading (Thread=9) count: 5 All Lock threads have completed.

17

Notice that although Increment was called five times for the unsafe test, the value of the counter never reaches five. Also, the start and stop notifications are interspersed among different threads. In the lock version, the start and stop notifications are paired for each thread, and the counter is correctly incremented to five.

Review

Module 7: Asynchronous Programming

.1 When and why would you use asynchronous programming techniques in an application? You should use asynchronous programming techniques in an application with significant user interaction to avoid blocking the user interface during slow method calls, such as XML Web service calls.

.2 In a Windows Forms application, what are the main steps to follow to use the asynchronous programming design pattern with an asynchronous callback for completion? The main steps are: 1. Create the asynchronous callback delegate. 2. Invoke the BeginOperation method, passing it the callback. 3. Inside the callback, invoke the EndOperation method for completion. 4. Return control to the main thread and update the user interface.

.3 List the four ways to complete an asynchronous call. Four ways to complete the asynchronous call are: Using a callback Polling Calling EndOperation Waiting on a handle

.4 Why do you need to return control to the main thread before updating the UI in Windows Forms applications? You need to return control to the main thread before updating the UI because Windows Forms controls can be safely accessed only from the main thread.

.5 What additional step must you follow to asynchronously call a method of any class? When you want to asynchronously call methods in classes without builtin asynchronous support, you must explicitly create the delegate for the method you want to invoke. After that, follow the same steps required to asynchronously call methods in a class with built-in asynchronous support.

Module 7: Asynchronous Programming

19

.6 If an asynchronous operation throws an exception, when does your code receive the exception? The exception is thrown when the EndOperation method is called.

.7 What keyword is provided by the C# language for controlling access by multiple threads to a block of code? The C# language provides the lock keyword to control access by multiple threads to a block of code.

Lab 7.1: Making Asynchronous Calls to an XML Web Service


Objectives After completing this lab, you will have demonstrated your ability to:

Make asynchronous calls by using the .NET Framework asynchronous design pattern. Convert synchronous calls to asynchronous calls by using the .NET Framework asynchronous design pattern. Use the Visual Studio .NET debugger to follow the flow of asynchronous calls.

Note This lab focuses on the concepts in Module 7, Asynchronous Programming, in Course 2555A, Developing Microsoft .NET Applications for Windows (Visual C# .NET). As a result, this lab may not comply with Microsoft security recommendations. Prerequisites Before working on this lab, you must have:

The knowledge and skills to develop a simple Windows Forms application by using a Visual Studio .NETcompatible programming language. The knowledge and skills to debug an application by using Visual Studio .NET. The knowledge and skills to call XML Web services and make asynchronous calls by using the .NET Framework asynchronous design pattern.

Scenario

The Expense Report application makes numerous calls to an XML Web service. To improve the responsiveness and usability of the application, all of the XML Web service calls should be made asynchronously. To make the calls asynchronous, you must perform the following tasks:

Convert the synchronous XML Web service calls to asynchronous calls.

Module 7: Asynchronous Programming


Write the method that handles the asynchronous callback. Write the method that updates the user interface.

In the starter code for this lab, the asynchronous callback method and user interface update method are already written, and some of the XML Web service calls are already converted. In this lab, you will convert the rest of the synchronous XML Web service calls to asynchronous calls and then use the Visual Studio debugger to follow the flow of the asynchronous calls in the resulting code. Lab Setup There are starter and solution files associated with this lab. Browse to install_folder\Labfiles\Lab07_1\Ex01\Starter to find the starter files, and browse to install_folder\Labfiles\Lab07_1\Ex01\Solution to find the solution files. If you performed a default installation of the course files, install_folder corresponds to C:\Program Files\Msdntrain\2555.

Estimated time to complete this lab: 45 minutes

Exercise 1 Converting Synchronous Calls to Asynchronous Calls


In this exercise, you will convert some synchronous XML Web service calls to asynchronous calls. You will also use the Visual Studio debugger to view the flow of asynchronous calls and test your application to ensure that it has the expected results.

Tasks
1. Open the ExpenseReport project in

Additional information For more information about opening a project file and starting an application, see the following resource:
a.

Visual Studio .NET. Browse to install_folder\Labfiles\Lab07_1\Ex01\Starter to find the project files.

The Visual Studio .NET Help documentation. For additional information about opening a project file, in Search, select the Search in titles only check box, then search by using the phrase Open Project Dialog Box. For additional information about starting an application in the Designer, in Index, search by using the phrase Debugging Windows Applications.

2. Open the ExpenseReportList source file, and view

a. See the TODO comments in the code for more

the code. Refer to the synchronous versions of the calls to see which parameters to pass: The first four parameters should be the same. The fifth parameter should not use the ref keyword in the asynchronous version. The sixth parameter should be the callback delegate. The seventh parameter should be null.

detailed information about the tasks that you must perform to convert the synchronous XML Web service calls in the constructor to asynchronous calls.
b. For more information about how to make

asynchronous calls, see the following resources: Practice: Making an Asynchronous Call to an XML Web Service in Module 7 Asynchronous Programming, in Course 2555A, Developing Microsoft .NET Applications for Windows (Visual C# .NET). Lesson: The Asynchronous Programming Model Design Pattern in Module 7 Asynchronous Programming, in Course

Module 7: Asynchronous Programming

21

2555A, Developing Microsoft .NET Applications for Windows (Visual C# .NET). The .NET Framework SDK documentation. For more information about the asynchronous design pattern, search by using the phrase Including Asynchronous Calls.

Tasks
3. View the flow of asynchronous code by setting

Additional information
a. For more information about debugging and

breakpoints in the ExpenseReportList constructor and the GetReportsCB and UpdateReportsUI methods.
a.

controlling the flow of asynchronous calls, see the following resources: Practice: Making an Asynchronous Call to an XML Web Service in Module 7 Asynchronous Programming, in Course 2555A, Developing Microsoft .NET Applications for Windows (Visual C# .NET). This practice contains information about how to debug an asynchronous call. Lesson: The Asynchronous Programming Model Design Pattern in Module 7 Asynchronous Programming, in Course 2555A, Developing Microsoft .NET Applications for Windows (Visual C# .NET). This lesson contains information about the flow of control of an asynchronous call.

Run the application in the Visual Studio debugger. Click View Submitted Reports. Step through the code, and make sure it executes as expected. Confirm the correct behavior in the user interface by making sure that the expense reports are downloaded asynchronously when a new list window is opened.

b.

Module 7: Asynchronous Programming

THIS PAGE INTENTIONALLY LEFT BLANK

You might also like