采用 Async 和 Await 的异步编程(Visual Basic)Asynchronous programming with Async and Await (Visual Basic)
通过使用异步编程,你可以避免性能瓶颈并增强应用程序的总体响应能力。You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. 但是,编写异步应用程序的传统技术可能比较复杂,使它们难以编写、调试和维护。However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.
Visual Studio 2012 引入了一种简便方法,即异步编程。此方法利用了 .NET Framework 4.5 及更高版本和 Windows 运行时中的异步支持。Visual Studio 2012 introduced a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and higher as well as in the Windows Runtime. 编译器可执行开发人员曾进行的高难度工作,且应用程序保留了一个类似于同步代码的逻辑结构。The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code. 因此,你只需做一小部分工作就可以获得异步编程的所有好处。As a result, you get all the advantages of asynchronous programming with a fraction of the effort.
本主题概述了何时以及如何使用异步编程,并包括指向包含详细信息和示例的支持主题的链接。This topic provides an overview of when and how to use async programming and includes links to support topics that contain details and examples.
异步编程提升响应能力Async improves responsiveness
异步对可能起阻止作用的活动(例如,应用程序访问 Web 时)至关重要。Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web. 对 Web 资源的访问有时很慢或会延迟。Access to a web resource sometimes is slow or delayed. 如果此类活动在同步过程中受阻,则整个应用程序必须等待。If such an activity is blocked within a synchronous process, the entire application must wait. 在异步过程中,应用程序可继续执行不依赖 Web 资源的其他工作,直至潜在阻止任务完成。In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes.
下表显示了异步编程提高响应能力的典型区域。The following table shows typical areas where asynchronous programming improves responsiveness. 列出的 .NET Framework 4.5 和 Windows 运行时 API 包含支持异步编程的方法。The listed APIs from the .NET Framework 4.5 and the Windows Runtime contain methods that support async programming.
应用程序区域Application area | 包含异步方法的受支持的 APISupporting APIs that contain async methods |
---|---|
Web 访问Web access | HttpClient, SyndicationClientHttpClient, SyndicationClient |
使用文件Working with files | StorageFile, StreamWriter, StreamReader, XmlReaderStorageFile, StreamWriter, StreamReader, XmlReader |
使用映像Working with images | MediaCapture, BitmapEncoder, BitmapDecoderMediaCapture, BitmapEncoder, BitmapDecoder |
WCF 编程WCF programming | 同步和异步操作Synchronous and Asynchronous Operations |
由于所有与用户界面相关的活动通常共享一个线程,因此,异步对访问 UI 线程的应用程序来说尤为重要。Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. 如果任何进程在同步应用程序中受阻,则所有进程都将受阻。If any process is blocked in a synchronous application, all are blocked. 你的应用程序停止响应,因此,你可能在其等待过程中认为它已经失败。Your application stops responding, and you might conclude that it has failed when instead it's just waiting.
使用异步方法时,应用程序将继续响应 UI。When you use asynchronous methods, the application continues to respond to the UI. 例如,你可以调整窗口的大小或最小化窗口;如果你不希望等待应用程序结束,则可以将其关闭。You can resize or minimize a window, for example, or you can close the application if you don't want to wait for it to finish.
当设计异步操作时,该基于异步的方法将自动传输的等效对象添加到可从中选择的选项列表中。The async-based approach adds the equivalent of an automatic transmission to the list of options that you can choose from when designing asynchronous operations. 开发人员只需要投入较少的工作量即可使你获取传统异步编程的所有优点。That is, you get all the benefits of traditional asynchronous programming but with much less effort from the developer.
异步方法更容易编写Async methods are easier to write
Visual Basic 中的 Async 和 Await 关键字是异步编程的核心。The Async and Await keywords in Visual Basic are the heart of async programming. 通过这两个关键字,可以使用 .NET Framework 或 Windows 运行时中的资源轻松创建异步方法(几乎与创建同步方法一样轻松)。By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. 使用 Async
和 Await
定义的异步方法简称为异步 (Async) 方法。Asynchronous methods that you define by using Async
and Await
are referred to as async methods.
下面的示例演示了一种异步方法。The following example shows an async method. 你应对代码中的几乎所有内容都非常熟悉。Almost everything in the code should look completely familiar to you. 注释调出你添加的用来创建异步的功能。The comments call out the features that you add to create the asynchrony.
此主题的末尾提供完整的 Windows Presentation Foundation (WPF) 示例文件,请从异步示例:“使用 Async 和 Await 的异步编程”示例下载此示例。You can find a complete Windows Presentation Foundation (WPF) example file at the end of this topic, and you can download the sample from Async Sample: Example from "Asynchronous Programming with Async and Await".
' Three things to note about writing an Async Function:
' - The function has an Async modifier.
' - Its return type is Task or Task(Of T). (See "Return Types" section.)
' - As a matter of convention, its name ends in "Async".
Async Function AccessTheWebAsync() As Task(Of Integer)
Using client As New HttpClient()
' Call and await separately.
' - AccessTheWebAsync can do other things while GetStringAsync is also running.
' - getStringTask stores the task we get from the call to GetStringAsync.
' - Task(Of String) means it is a task which returns a String when it is done.
Dim getStringTask As Task(Of String) =
client.GetStringAsync("https://docs.microsoft.com/dotnet")
' You can do other work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork()
' The Await operator suspends AccessTheWebAsync.
' - AccessTheWebAsync does not continue until getStringTask is complete.
' - Meanwhile, control returns to the caller of AccessTheWebAsync.
' - Control resumes here when getStringTask is complete.
' - The Await operator then retrieves the String result from getStringTask.
Dim urlContents As String = Await getStringTask
' The Return statement specifies an Integer result.
' A method which awaits AccessTheWebAsync receives the Length value.
Return urlContents.Length
End Using
End Function
如果 AccessTheWebAsync
在调用 GetStringAsync
和等待其完成期间不能进行任何工作,则你可以通过在下面的单个语句中调用和等待来简化代码。If AccessTheWebAsync
doesn't have any work that it can do between calling GetStringAsync
and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.
Dim urlContents As String = Await client.GetStringAsync()
以下特征总结了使上一个示例成为异步方法的原因:The following characteristics summarize what makes the previous example an async method:
方法签名包含
Async
修饰符。The method signature includes anAsync
modifier.按照约定,异步方法的名称以“Async”后缀结尾。The name of an async method, by convention, ends with an "Async" suffix.
返回类型为下列类型之一:The return type is one of the following types:
- 如果你的方法有操作数为 TResult 类型的返回语句,则为 Task<TResult>。Task<TResult> if your method has a return statement in which the operand has type TResult.
- 如果你的方法没有返回语句或具有没有操作数的返回语句,则为 Task。Task if your method has no return statement or has a return statement with no operand.
- Sub:如果要编写异步事件处理程序。Sub if you're writing an async event handler.
有关详细信息,请参见本主题后面的“返回类型和参数”。For more information, see "Return Types and Parameters" later in this topic.
方法通常包含至少一个 await 表达式,该表达式标记一个点,在该点上,直到等待的异步操作完成方法才能继续。The method usually includes at least one await expression, which marks a point where the method can't continue until the awaited asynchronous operation is complete. 同时,将方法挂起,并且控制返回到方法的调用方。In the meantime, the method is suspended, and control returns to the method's caller. 本主题的下一节将解释悬挂点发生的情况。The next section of this topic illustrates what happens at the suspension point.
在异步方法中,可使用提供的关键字和类型来指示需要完成的操作,且编译器会完成其余操作,其中包括持续跟踪控制以挂起方法返回等待点时发生的情况。In async methods, you use the provided keywords and types to indicate what you want to do, and the compiler does the rest, including keeping track of what must happen when control returns to an await point in a suspended method. 一些常规流程(例如,循环和异常处理)在传统异步代码中处理起来可能很困难。Some routine processes, such as loops and exception handling, can be difficult to handle in traditional asynchronous code. 在异步方法中,元素的编写频率与同步解决方案相同且此问题得到解决。In an async method, you write these elements much as you would in a synchronous solution, and the problem is solved.
若要详细了解旧版 .NET Framework 中的异步性,请参阅 TPL 和传统 .NET Framework 异步编程。For more information about asynchrony in previous versions of the .NET Framework, see TPL and Traditional .NET Framework Asynchronous Programming.
异步方法中发生的情况What happens in an Async method
异步编程中最需弄清的是控制流是如何从方法移动到方法的。The most important thing to understand in asynchronous programming is how the control flow moves from method to method. 下图可引导你完成此过程:The following diagram leads you through the process:
图中的数字对应于以下步骤:The numbers in the diagram correspond to the following steps:
事件处理程序调用并等待
AccessTheWebAsync
异步方法。An event handler calls and awaits theAccessTheWebAsync
async method.AccessTheWebAsync
可创建 HttpClient 实例并调用 GetStringAsync 异步方法以下载网站内容作为字符串。AccessTheWebAsync
creates an HttpClient instance and calls the GetStringAsync asynchronous method to download the contents of a website as a string.GetStringAsync
中发生了某种情况,该情况挂起了它的进程。Something happens inGetStringAsync
that suspends its progress. 可能必须等待网站下载或一些其他阻止活动。Perhaps it must wait for a website to download or some other blocking activity. 为避免阻止资源,GetStringAsync
会将控制权出让给其调用方AccessTheWebAsync
。To avoid blocking resources,GetStringAsync
yields control to its caller,AccessTheWebAsync
.GetStringAsync
返回 Task<TResult>,其中 TResult 为字符串,并且AccessTheWebAsync
将任务分配给getStringTask
变量。GetStringAsync
returns a Task<TResult> where TResult is a string, andAccessTheWebAsync
assigns the task to thegetStringTask
variable. 该任务表示调用GetStringAsync
的正在进行的进程,其中承诺当工作完成时产生实际字符串值。The task represents the ongoing process for the call toGetStringAsync
, with a commitment to produce an actual string value when the work is complete.由于尚未等待
getStringTask
,因此,AccessTheWebAsync
可以继续执行不依赖于GetStringAsync
得出的最终结果的其他工作。BecausegetStringTask
hasn't been awaited yet,AccessTheWebAsync
can continue with other work that doesn't depend on the final result fromGetStringAsync
. 该任务由对同步方法DoIndependentWork
的调用表示。That work is represented by a call to the synchronous methodDoIndependentWork
.DoIndependentWork
是完成其工作并返回其调用方的同步方法。DoIndependentWork
is a synchronous method that does its work and returns to its caller.AccessTheWebAsync
已运行完毕,可以不受getStringTask
的结果影响。AccessTheWebAsync
has run out of work that it can do without a result fromgetStringTask
. 接下来,AccessTheWebAsync
需要计算并返回已下载的字符串的长度,但该方法只有在获得字符串的情况下才能计算该值。AccessTheWebAsync
next wants to calculate and return the length of the downloaded string, but the method can't calculate that value until the method has the string.因此,
AccessTheWebAsync
使用一个 await 运算符来挂起其进度,并把控制权交给调用AccessTheWebAsync
的方法。Therefore,AccessTheWebAsync
uses an await operator to suspend its progress and to yield control to the method that calledAccessTheWebAsync
.AccessTheWebAsync
将Task<int>
(Visual Basic 中的Task(Of Integer)
)返回给调用方。AccessTheWebAsync
returns aTask<int>
(Task(Of Integer)
in Visual Basic) to the caller. 该任务表示对产生下载字符串长度的整数结果的一个承诺。The task represents a promise to produce an integer result that's the length of the downloaded string.备注
如果
GetStringAsync
(因此getStringTask
)在AccessTheWebAsync
等待前完成,则控制会保留在AccessTheWebAsync
中。IfGetStringAsync
(and thereforegetStringTask
) is complete beforeAccessTheWebAsync
awaits it, control remains inAccessTheWebAsync
. 如果异步调用过程 (AccessTheWebAsync
) 已完成,并且 AccessTheWebSync 不必等待最终结果,则挂起然后返回到getStringTask
将造成成本浪费。The expense of suspending and then returning toAccessTheWebAsync
would be wasted if the called asynchronous process (getStringTask
) has already completed and AccessTheWebSync doesn't have to wait for the final result.在调用方内部(此示例中的事件处理程序),处理模式将继续。Inside the caller (the event handler in this example), the processing pattern continues. 在等待结果前,调用方可以开展不依赖于
AccessTheWebAsync
结果的其他工作,否则就需等待片刻。The caller might do other work that doesn't depend on the result fromAccessTheWebAsync
before awaiting that result, or the caller might await immediately. 事件处理程序等待AccessTheWebAsync
,而AccessTheWebAsync
等待GetStringAsync
。The event handler is waiting forAccessTheWebAsync
, andAccessTheWebAsync
is waiting forGetStringAsync
.GetStringAsync
完成并生成一个字符串结果。GetStringAsync
completes and produces a string result. 字符串结果不是通过按你预期的方式调用GetStringAsync
所返回的。The string result isn't returned by the call toGetStringAsync
in the way that you might expect. (请记住,此方法已在步骤 3 中返回一个任务。)相反,字符串结果存储在表示完成方法getStringTask
的任务中。(Remember that the method already returned a task in step 3.) Instead, the string result is stored in the task that represents the completion of the method,getStringTask
. await 运算符从getStringTask
中检索结果。The await operator retrieves the result fromgetStringTask
. 赋值语句将检索到的结果赋给urlContents
。The assignment statement assigns the retrieved result tourlContents
.当
AccessTheWebAsync
具有字符串结果时,该方法可以计算字符串长度。WhenAccessTheWebAsync
has the string result, the method can calculate the length of the string. 然后,AccessTheWebAsync
工作也将完成,并且等待事件处理程序可继续使用。Then the work ofAccessTheWebAsync
is also complete, and the waiting event handler can resume. 在此主题结尾处的完整示例中,可确认事件处理程序检索并打印长度结果的值。In the full example at the end of the topic, you can confirm that the event handler retrieves and prints the value of the length result.
如果你不熟悉异步编程,请花 1 分钟时间考虑同步行为和异步行为之间的差异。If you are new to asynchronous programming, take a minute to consider the difference between synchronous and asynchronous behavior. 当其工作完成时(第 5 步)会返回一个同步方法,但当其工作挂起时(第 3 步和第 6 步),异步方法会返回一个任务值。A synchronous method returns when its work is complete (step 5), but an async method returns a task value when its work is suspended (steps 3 and 6). 在异步方法最终完成其工作时,任务会标记为已完成,而结果(如果有)将存储在任务中。When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the task.
若要详细了解控制流,请参阅异步程序中的控制流 (Visual Basic)。For more information about control flow, see Control Flow in Async Programs (Visual Basic).
API 异步方法API Async Methods
你可能想知道从何处可以找到 GetStringAsync
等支持异步编程的方法。You might be wondering where to find methods such as GetStringAsync
that support async programming. .NET Framework 4.5 或更高版本包含许多与 Async
和 Await
结合使用的成员。The .NET Framework 4.5 or higher contains many members that work with Async
and Await
. 可以通过附加到成员名称的 "Async" 后缀和 Task 或 Task<TResult>的返回类型识别这些成员。You can recognize these members by the "Async" suffix that's attached to the member name and a return type of Task or Task<TResult>. 例如,System.IO.Stream
类包含 CopyToAsync、ReadAsync 和 WriteAsync 等方法,以及同步方法 CopyTo、Read 和 Write。For example, the System.IO.Stream
class contains methods such as CopyToAsync, ReadAsync, and WriteAsync alongside the synchronous methods CopyTo, Read, and Write.
Windows 运行时也包含许多可以在 Windows 应用中与 Async
和 Await
结合使用的方法。The Windows Runtime also contains many methods that you can use with Async
and Await
in Windows apps. 有关详细信息和示例方法,请参阅在或 Visual Basic C#中调用异步 api、异步编程(Windows 运行时应用)和System.threading.tasks.task.whenany: .NET Framework 与 Windows 运行时之间的桥接。For more information and example methods, see Call asynchronous APIs in C# or Visual Basic, Asynchronous programming (Windows Runtime apps), and WhenAny: Bridging between the .NET Framework and the Windows Runtime.
线程Threads
异步方法旨在成为非阻止操作。Async methods are intended to be non-blocking operations. 异步方法中的 Await
表达式在等待的任务正在运行时不会阻止当前线程。An Await
expression in an async method doesn't block the current thread while the awaited task is running. 相反,表达式在继续时注册方法的其余部分并将控制返回到异步方法的调用方。Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.
Async
和 Await
关键字不会创建其他线程。The Async
and Await
keywords don't cause additional threads to be created. 异步方法不需要多线程处理,因为异步方法不会在其自己的线程上运行。Async methods don't require multi-threading because an async method doesn't run on its own thread. 只有当方法处于活动状态时,该方法将在当前同步上下文中运行并使用线程上的时间。The method runs on the current synchronization context and uses time on the thread only when the method is active. 可以使用 Task.Run 将占用大量 CPU 的工作移到后台线程,但是后台线程不会帮助正在等待结果的进程变为可用状态。You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.
对于异步编程而言,该基于异步的方法优于几乎每个用例中的现有方法。The async-based approach to asynchronous programming is preferable to existing approaches in almost every case. 具体而言,此方法比对 i/o 限制操作 BackgroundWorker 更好,因为代码更简单且无需防范争用情况。In particular, this approach is better than BackgroundWorker for I/O-bound operations because the code is simpler and you don't have to guard against race conditions. 结合 Task.Run 使用时,异步编程比 BackgroundWorker 更适用于 CPU 绑定的操作,因为异步编程将运行代码的协调细节与 Task.Run
传输至线程池的工作区分开来。In combination with Task.Run, async programming is better than BackgroundWorker for CPU-bound operations because async programming separates the coordination details of running your code from the work that Task.Run
transfers to the threadpool.
Async 和 AwaitAsync and Await
如果使用 Async 修饰符将某种方法指定为异步方法,即启用以下两种功能。If you specify that a method is an async method by using an Async modifier, you enable the following two capabilities.
标记的异步方法可以使用 Await 来指定暂停点。The marked async method can use Await to designate suspension points. await 运算符通知编译器异步方法只有直到等待的异步过程完成才能继续通过该点。The await operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete. 同时,控制返回至异步方法的调用方。In the meantime, control returns to the caller of the async method.
异步方法在
Await
表达式执行时暂停并不构成方法退出,只会导致Finally
代码块不运行。The suspension of an async method at anAwait
expression doesn't constitute an exit from the method, andFinally
blocks don't run.标记的异步方法本身可以通过调用它的方法等待。The marked async method can itself be awaited by methods that call it.
异步方法通常包含 Await
运算符的一个或多个实例,但缺少 Await
表达式也不会导致生成编译器错误。An async method typically contains one or more occurrences of an Await
operator, but the absence of Await
expressions doesn't cause a compiler error. 如果异步方法未使用 Await
运算符标记暂停点,则该方法会作为同步方法执行,即使有 Async
修饰符,也不例外。If an async method doesn't use an Await
operator to mark a suspension point, the method executes as a synchronous method does, despite the Async
modifier. 编译器将为此类方法发布一个警告。The compiler issues a warning for such methods.
Async
和 Await
都是上下文关键字。Async
and Await
are contextual keywords. 有关更多信息和示例,请参见以下主题:For more information and examples, see the following topics:
返回类型和参数Return types and parameters
在 .NET Framework 编程中,异步方法通常返回 Task 或 Task<TResult>。In .NET Framework programming, an async method typically returns a Task or a Task<TResult>. 在异步方法中,Await
运算符应用于通过调用另一个异步方法返回的任务。Inside an async method, an Await
operator is applied to a task that's returned from a call to another async method.
如果方法包含指定 Task<TResult> 类型操作数的 Return 语句,将 TResult
指定为返回类型。You specify Task<TResult> as the return type if the method contains a Return statement that specifies an operand of type TResult
.
如果方法不含任何 return 语句或包含不返回操作数的 return 语句,则将 Task
用作返回类型。You use Task
as the return type if the method has no return statement or has a return statement that doesn't return an operand.
下面的示例演示如何声明并调用可返回 Task<TResult> 或 Task 的方法:The following example shows how you declare and call a method that returns a Task<TResult> or a Task:
' Signature specifies Task(Of Integer)
Async Function TaskOfTResult_MethodAsync() As Task(Of Integer)
Dim hours As Integer
' . . .
' Return statement specifies an integer result.
Return hours
End Function
' Calls to TaskOfTResult_MethodAsync
Dim returnedTaskTResult As Task(Of Integer) = TaskOfTResult_MethodAsync()
Dim intResult As Integer = Await returnedTaskTResult
' or, in a single statement
Dim intResult As Integer = Await TaskOfTResult_MethodAsync()
' Signature specifies Task
Async Function Task_MethodAsync() As Task
' . . .
' The method has no return statement.
End Function
' Calls to Task_MethodAsync
Task returnedTask = Task_MethodAsync()
Await returnedTask
' or, in a single statement
Await Task_MethodAsync()
每个返回的任务表示正在进行的工作。Each returned task represents ongoing work. 任务可封装有关异步进程状态的信息,如果未成功,则最后会封装来自进程的最终结果或进程引发的异常。A task encapsulates information about the state of the asynchronous process and, eventually, either the final result from the process or the exception that the process raises if it doesn't succeed.
异步方法还可以是 Sub
方法。An async method can also be a Sub
method. 这种返回类型主要用于在需要返回类型的情况下定义事件处理程序。This return type is used primarily to define event handlers, where a return type is required. 异步事件处理程序通常用作异步程序的起始点。Async event handlers often serve as the starting point for async programs.
不能等待 Sub
过程的异步方法,调用方无法捕获该方法引发的任何异常。An async method that's a Sub
procedure can't be awaited, and the caller can't catch any exceptions that the method throws.
异步方法无法声明 ByRef 参数,但可以调用包含此类参数的方法。An async method can't declare ByRef parameters, but the method can call methods that have such parameters.
有关详细信息和示例,请参阅异步返回类型 (Visual Basic)。For more information and examples, see Async Return Types (Visual Basic). 若要详细了解如何在异步方法中捕获异常,请参阅 Try...Catch...Finally 语句。For more information about how to catch exceptions in async methods, see Try...Catch...Finally Statement.
Windows 运行时编程中的异步 API 具有下列返回类型之一(类似于任务):Asynchronous APIs in Windows Runtime programming have one of the following return types, which are similar to tasks:
- IAsyncOperation<TResult>(对应于 Task<TResult>)IAsyncOperation<TResult>, which corresponds to Task<TResult>
- IAsyncAction(对应于 Task)IAsyncAction, which corresponds to Task
- IAsyncActionWithProgress<TProgress>
- IAsyncOperationWithProgress<TResult, TProgress>
有关详细信息和示例,请参阅在或 Visual Basic 中C#调用异步 api。For more information and an example, see Call asynchronous APIs in C# or Visual Basic.
命名约定Naming convention
按照约定,将“Async”追加到包含 Async
修饰符的方法的名称中。By convention, you append "Async" to the names of methods that have an Async
modifier.
如果某一约定中的事件、基类或接口协定建议其他名称,则可以忽略此约定。You can ignore the convention where an event, base class, or interface contract suggests a different name. 例如,你不应重命名常用事件处理程序,例如 Button1_Click
。For example, you shouldn't rename common event handlers, such as Button1_Click
.
相关主题和示例 (Visual Studio)Related topics and samples (Visual Studio)
完整的示例Complete Example
下面的代码来自于本主题介绍的 Windows Presentation Foundation (WPF) 应用程序的 MainWindow.xaml.vb 文件。The following code is the MainWindow.xaml.vb file from the Windows Presentation Foundation (WPF) application that this topic discusses. 可以从异步示例:“使用 Async 和 Await 的异步编程”示例下载示例。You can download the sample from Async Sample: Example from "Asynchronous Programming with Async and Await".
Imports System.Net.Http
' Example that demonstrates Asynchronous Progamming with Async and Await.
' It uses HttpClient.GetStringAsync to download the contents of a website.
' Sample Output:
' Working . . . . . . .
'
' Length of the downloaded string: 39678.
Class MainWindow
' Mark the event handler with Async so you can use Await in it.
Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
' Call and await immediately.
' StartButton_Click suspends until AccessTheWebAsync is done.
Dim contentLength As Integer = Await AccessTheWebAsync()
ResultsTextBox.Text &= $"{vbCrLf}Length of the downloaded string: {contentLength}.{vbCrLf}"
End Sub
' Three things to note about writing an Async Function:
' - The function has an Async modifier.
' - Its return type is Task or Task(Of T). (See "Return Types" section.)
' - As a matter of convention, its name ends in "Async".
Async Function AccessTheWebAsync() As Task(Of Integer)
Using client As New HttpClient()
' Call and await separately.
' - AccessTheWebAsync can do other things while GetStringAsync is also running.
' - getStringTask stores the task we get from the call to GetStringAsync.
' - Task(Of String) means it is a task which returns a String when it is done.
Dim getStringTask As Task(Of String) =
client.GetStringAsync("https://docs.microsoft.com/dotnet")
' You can do other work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork()
' The Await operator suspends AccessTheWebAsync.
' - AccessTheWebAsync does not continue until getStringTask is complete.
' - Meanwhile, control returns to the caller of AccessTheWebAsync.
' - Control resumes here when getStringTask is complete.
' - The Await operator then retrieves the String result from getStringTask.
Dim urlContents As String = Await getStringTask
' The Return statement specifies an Integer result.
' A method which awaits AccessTheWebAsync receives the Length value.
Return urlContents.Length
End Using
End Function
Sub DoIndependentWork()
ResultsTextBox.Text &= $"Working . . . . . . .{vbCrLf}"
End Sub
End Class
另请参阅See also
反馈
正在加载反馈...