C# 基于事件的异步模式

EventBasedAsyncPattern 方法使用了基于事件的异步模式。这个模式定义了一个带有 “Async” 后缀的方法。示例代码再次使用了WebClient 类。对于同步方法DownloadString,WebClient类提供了一个异步变体方法 DownloadStringAsync。当请求完成时,会触发 DownloadStringCompleted事件。使用此事件的事件处理程序,可以检索结果。DownloadStringCompleted事件类型为DownloadStringCompletedEventHandler。第二个参数是 DownloadStringCompletedEventArgs 类型。这个参数通过 Result 属性返回结果字符串:.

private static void EventBasedAsyncPattern(){  Console.WriteLine(nameof(EventBasedAsyncPattern));  using (var client = new WebClient())  {    client.DownloadStringCompleted += (sender, e) =>    {      Console.WriteLine(e.Result.Substring(0,100));    };    client.DownloadStringAsync(new Uri(url));    Console.WriteLine();  }}

使用 DownloadStringCompleted 事件,事件处理程序将通过保存同步上下文的线程来调用。在 Windows 窗体、WPF 和 UWP 中,这就是 UI 线程。因此,可以直接从事件处理程序中访问 UI 元素。与异步模式相比,这是该模式的一大优点。

基于事件的异步模式和同步编程之间的区别在于方法调用的顺序;与同步方法调用相比,顺序颠倒了。调用异步方法之前,需要定义这个方法完成时发生什么。