
C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#
.pdfModule 14 (Optional): Threading and Asynchronous Programming |
103 |
|
|
|
|
Exercise 4
Making an Asynchronous Method Call
In this exercise, you will add code that uses a delegate object to begin an asynchronous invocation of the WriteLog method of the MyLogger class. The code will specify a method to be called when the WriteLog method completes. You will add code to this method to obtain the results of the WriteLog method and post the results to the form’s status bar.
! Create the event handler code that initiates the asynchronous write
1.In Form1.cs, locate the following comment for the button4_Click method of the Form1 class:
// TODO - Exercise 4.1: Add code to begin asynchronous! log write
2.Set the statusBar1.Text property to an empty string.
3.Create a delegate named wld of type WriteLogDelegate that refers to the WriteLog static method of the MyLogger class.
4.Create a delegate object named cb of type AsyncCallback that refers to the current Form1 object’s AsynchronousWriteResults method.
5.Initialize a variable named ar of type IAsyncResult to the value that is returned by invoking the wld object’s BeginInvoke method.
BeginInvoke should include the following three parameters: a. The textBox2 Text property
b. The cb delegate object c. null

104Module 14 (Optional): Threading and Asynchronous Programming
!Create the code that is called when the asynchronous method call completes
1.In Form1.cs, locate the following comment for the
AsynchronousWriteResults method of the Form1 class:
// TODO - Exercise 4.2: Add code to this callback method to handle ! the results of asynchronous log write
2.Create a delegate object name wld of type WriteLogDelegate and set wld to refer to the method that was previously specified in the button4_Click method’s BeginInvoke method call by doing the following:
a. Explicitly cast the parameter that is named ar of type IAsyncResult to type AsyncResult and get its AsyncDelegate property.
b. Explicitly cast the result of the preceding step to type WriteLogDelegate and assign this value to wld.
3.Create a try/catch block and in the try section, add code to do the following:
a. Initialize a variable named count of type int to the result of calling the wld object’s EndInvoke method with the single parameter named ar.
b. Assign to the existing variable named resultString of type string the following value:
"Log written asynchronously, " + count.ToString()
4.In the try/catch block’s catch section, add code to do the following:
a.Catch exceptions of the type InvalidOperationException.
b.Assign to the existing variable named resultString of type string the following value:
"Invalid Operation - Asynchronous write failed because ! logger was stopped"
5.To update the form’s control on the thread that originally created the control, call the BeginInvoke method of the current Form1 object.
BeginInvoke takes a single parameter that is a delegate of type MethodInvoker that refers to the current Form1 object’s
UpdateAsynchronousWriteStatus method.
!Test the application
1.Build and run the application by using Visual Studio .NET. Ensure that you have deleted the file Log.txt that was created in the preceding exercise.
2.In the Text To Log field, type Hello Asynchronous World.
3.Click Start Logger.
Note that the Logger State Indicator progress bar is advancing and note the following message in the status bar.
“Logger started”
Module 14 (Optional): Threading and Asynchronous Programming |
105 |
|
|
|
|
4.Click Asynchronous Write, and note that the progress bar continues to advance.
After a pause of 2 seconds, the following message is displayed in the status bar:
“Log written asynchronously, 1”
5.Click Asynchronous Write, and note that after a pause of 2 seconds the message in the status bar changes to:
“Log written asynchronously, 2”
6.Click Asynchronous Write twice in quick succession, and after the message “Log written asynchronously, 4” is displayed in the status bar. Click Stop Logger.
Note that the Logger State Indicator progress bar stops advancing and note that the following message is displayed in the status bar:
“Logger stopped”
7.Use Visual Studio .NET to view the file Log.txt that was created in the same folder as the multithreading application’s executable program:
<install folder>\Labs\Lab14\Starter\Multithreading\bin\Debug You should see output that is similar to the following:
StartLogger - Time: 12:04:27 PM Wednesday, September 19, 2001
Logger Alive: 12:04:27 PM Wednesday, September 19, 2001
Count:1 Text: Hello Asynchronous World - Time:12:04:30 PM
Wednesday, September 19, 2001
Logger Alive: 12:04:32 PM Wednesday, September 19, 2001
Count:2 Text: Hello Asynchronous World - Time:12:04:33 PM
Wednesday, September 19, 2001
Count:3 Text: Hello Asynchronous World - Time:12:04:36 PM
Wednesday, September 19, 2001
Logger Alive: 12:04:37 PM Wednesday, September 19, 2001
Count:4 Text: Hello Asynchronous World - Time:12:04:38 PM
Wednesday, September 19, 2001
StopLogger - Time:12:04:41 PM Wednesday, September 19, 2001
8. Stop the application and delete Log.txt.

Module 14 (Optional): Threading and Asynchronous Programming |
107 |
|
|
|
|
7.Use Visual Studio .NET to view the file Log.txt that was created in the same folder as the multithreading application’s executable program:
<install folder>\Labs\Lab14\Starter\Multithreading\bin\Debug You should see output that is similar to the following:
StartLogger - Time: 12:40:24 PM Wednesday, September 19, 2001
Logger Alive: 12:40:24 PM Wednesday, September 19, 2001
Count:1 Text: Hello Asynchronous World - Time:12:40:28 PM
Wednesday, September 19, 2001
Logger Alive: 12:40:30 PM Wednesday, September 19, 2001
Count:2 Text: Hello Asynchronous World - Time:12:40:30 PM
Wednesday, September 19, 2001
Logger Alive: 12:40:35 PM Wednesday, September 19, 2001
Count:3 Text: Hello Asynchronous World - Time:12:40:35 PM
Wednesday, September 19, 2001
Count:3 Text: Hello Asynchronous World - Time:12:40:35 PM
Wednesday, September 19, 2001
Logger Alive: 12:40:39 PM Wednesday, September 19, 2001
Logger Alive: 12:40:44 PM Wednesday, September 19, 2001
StopLogger - Time:12:40:44 PM Wednesday, September 19, 2001
Note Because of the race condition during the last two asynchronous writes, the write counter is the same for both of these writes.
8. Stop the application and delete Log.txt.

Module 14 (Optional): Threading and Asynchronous Programming |
109 |
|
|
|
|
4.If you want to get or set properties, or call methods on a control from a background thread, what must you do?
You must marshal the call to the thread on which the control was created by using one of the control’s thread safe methods: Invoke, BeginInvoke, and EndInvoke.
5.In the second part of an asynchronous call operation, name the four ways that the caller can know when the asynchronous operation has completed.
Callback method, poll, call end method, wait for event.

|
|
|
|
Module 15 (Optional): |
|
|
Interoperating Between |
|
|
Managed and |
|
Contents |
Unmanaged Code |
|
|
|
|
Overview |
1 |
|
Integration Services |
2 |
|
Platform Invoke |
7 |
|
Lab 15.1: Calling Win32 APIs |
16 |
|
Calling COM Objects from Managed Code |
20 |
|
Lab 15.2: Calling COM Objects |
39 |
|
Calling .NET Objects from COM Objects |
43 |
|
Review |
55 |
|
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, places or events 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 written permission of Microsoft Corporation.
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.
2001-2002 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their respective owners.