Download visual basic unleashed PDF

Titlevisual basic unleashed
File Size1.3 MB
Total Pages116
Table of Contents
                            Table of Contents
Introduction
Code Samples and Software Requirements
42 Asynchronous Programming
	Overview of Asynchrony
	The Old-Fashioned Way: Event-Based Asynchrony
	The Old-Fashioned Way: The Asynchronous Programming Model
	The Modern Way: The Async Pattern
	Getting Started with Async/Await
	Exception Handling in Async
	Implementing Task-Based Asynchrony
	Cancellation and Progress
	Asynchronous Lambda Expressions
	Asynchronous I/O File Operations in .NET 4.6
	Debugging Tasks
	Summary
Index
	A
	B
	C
	D
	E
	F
	G
	H
	I
	J
	K
	L
	M
	N
	O
	P
	Q
	R
	S
	T
	U
	V
	W
	X
	Y-Z
                        
Document Text Contents
Page 1

http://www.facebook.com/share.php?u=http://www.informIT.com/title/9780672334504
http://twitter.com/?status=RT: download a free sample chapter http://www.informit.com/title/9780672334504
https://plusone.google.com/share?url=http://www.informit.com/title/9780672334504
http://www.linkedin.com/shareArticle?mini=true&url=http://www.informit.com/title/9780672334504
http://www.stumbleupon.com/submit?url=http://www.informit.com/title/9780672334504/Free-Sample-Chapter

Page 2

UNLEASHED

800 East 96th Street, Indianapolis, Indiana 46240 USA

Alessandro Del Sole

Visual Basic®
2015

Page 58

CHAPTER 42 Asynchronous Programming1170

Report receives as an argument an object of the same type that you assigned as the
generic argument of the Progress class declaration in this case a counter of type Integer
that is incremented every time a feed is downloaded. If you run this code, every time a
feed is returned, the progress is also shown in the user interface, as demonstrated in Figure
42.6 .



FIGURE 42.6 Reporting the progress of an asynchronous method.

This pattern makes reporting the progress of a task and in real-world applications, such
as WPF and Windows apps, easy. It also makes updating controls like the ProgressBar
incredibly simple by assigning to such controls the value stored in the instance of the
Progress class.

Asynchronous Lambda Expressions
Methods can be asynchronous, but so can lambda expressions. To be asynchronous, a
lambda must have the Async modifier and must return Task or Task(Of T) , but it cannot
accept ByRef arguments and cannot be an iterator function. A lambda can be asynchro-
nous when its code uses the Await operator to wait for a Task result. An example of asyn-
chronous lambdas is with event handlers. For instance, you might need to wait for the
result of a task when an event is raised, as in the following code snippet that handles a
button’s Click :

AddHandler Me.Button1.Click, Async Sub(sender, e)

Await DoSomeWorkAsync

End Sub

You do not need an asynchronous lambda if the work you are going to execute does
not return a Task . Another typical usage of asynchronous lambdas is with Task.Run . The
following code shows the same example described when introducing Task.Run , but now

Page 59

Asynchronous I/O File Operations in .NET 4.6 1171
4

2

the lambda that starts the intensive work is marked with Async and the method that actu-
ally performs intensive computations returns a Task so that it can be awaited:

Private Async Sub RunIntensiveWorkAsync()

cancellationToken = New CancellationTokenSource

'This runs on the UI thread

Console.WriteLine("Starting...")



Try

'This runs on a Thread Pool thread

Dim result As Integer = Await Task.Run(Async Function()

Dim workResult As Integer = _

Await _

SimulateIntensiveWorkAsync()

Return workResult

End Function)

'This runs again on the UI thread

Console.WriteLine("Finished")

Catch ex As OperationCanceledException

Console.WriteLine("Canceled by the user.")

Catch ex As Exception



End Try

Console.ReadLine()

End Sub



Private Async Function SimulateIntensiveWorkAsync() As Task(Of Integer)

Dim delay As Integer = 1000

Await Task.Delay(delay)

Return delay

End Function

This code simulates CPU-intensive work inside an asynchronous method. However, this is
not best practice and should be avoided when possible. Here it is shown for demonstration
purposes only. For additional tips about asynchronous methods, visit http://channel9.
msdn.com/Series/Three-Essential-Tips-for-Async/Async-Library-Methods-Shouldn-t-Lie .

Asynchronous I/O File Operations in .NET 4.6
Before .NET Framework 4.5, you could perform asynchronous operations over files and
streams by using the Asynchronous Programming Model and methods such as Stream.
BeginRead and Stream.EndRead . This kind of approach can be good, but it has the limita-
tions described in the section “Getting Started with Async / Await ” in this chapter. With
.NET Framework 4.5 and after, asynchronous I/O operations can be simplified by using
the Async pattern and by implementing asynchronous versions of methods that work
with files and stream to avoid blocking the main thread. Such methods are exposed by the

http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-Library-Methods-Shouldn-t-Lie
http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-Library-Methods-Shouldn-t-Lie

Page 115

Register the Addison-Wesley, Exam
Cram, Prentice Hall, Que, and
Sams products you own to unlock
great benefi ts.

To begin the registration process,
simply go to informit.com/register
to sign in or create an account.
You will then be prompted to enter
the 10- or 13-digit ISBN that appears
on the back cover of your product.

informIT.com
THE TRUSTED TECHNOLOGY LEARNING SOURCE

Addison-Wesley | Cisco Press | Exam Cram
IBM Press | Que | Prentice Hall | Sams

SAFARI BOOKS ONLINE

About InformIT — THE TRUSTED TECHNOLOGY LEARNING SOURCE

INFORMIT IS HOME TO THE LEADING TECHNOLOGY PUBLISHING IMPRINTS
Addison-Wesley Professional, Cisco Press, Exam Cram, IBM Press, Prentice Hall

Professional, Que, and Sams. Here you will gain access to quality and trusted content and

resources from the authors, creators, innovators, and leaders of technology. Whether you’re

looking for a book on a new technology, a helpful article, timely newsletters, or access to

the Safari Books Online digital library, InformIT has a solution for you.

Registering your products can unlock
the following benefi ts:

• Access to supplemental content,
including bonus chapters,
source code, or project fi les.

• A coupon to be used on your
next purchase.

Registration benefi ts vary by product.
Benefi ts will be listed on your Account
page under Registered Products.

informit.com/register

THIS PRODUCT

Page 116

InformIT is a brand of Pearson and the online presence

for the world’s leading technology publishers. It’s your source

for reliable and qualified content and knowledge, providing

access to the top brands, authors, and contributors from

the tech community.

informIT.com THE TRUSTED TECHNOLOGY LEARNING SOURCE

LearnIT at InformIT
Looking for a book, eBook, or training video on a new technology? Seek-

ing timely and relevant information and tutorials? Looking for expert opin-

ions, advice, and tips? InformIT has the solution.

• Learn about new releases and special promotions by

subscribing to a wide variety of newsletters.

Visit informit.com/newsletters.

• Access FREE podcasts from experts at informit.com/podcasts.

• Read the latest author articles and sample chapters at

informit.com/articles.

• Access thousands of books and videos in the Safari Books

Online digital library at safari.informit.com.

• Get tips from expert blogs at informit.com/blogs.

Visit informit.com/learn to discover all the ways you can access the

hottest technology content.

informIT.com THE TRUSTED TECHNOLOGY LEARNING SOURCE

Are You Part of the IT Crowd?
Connect with Pearson authors and editors via RSS feeds, Facebook,

Twitter, YouTube, and more! Visit informit.com/socialconnect.

Similer Documents