APM之基于事件的异步模式(EAP)-2

EAP是针对Windows窗体开发提供的方便使用的异步模式,可以在IDE中可视化的设计和使用

            // The System.Net.WebClient class supports the Event-based Asynchronous Pattern
            WebClient wc = new WebClient();
 
            // When a string completes downloading, the WebClient object raises the 
            // DownloadStringCompleted event which will invoke our ProcessString method         
            wc.DownloadStringCompleted += (s, e) =>
            {
                System.Windows.Forms.MessageBox.Show((e.Error != null) ? e.Error.Message : e.Result);
            };
 
            // Start the asynchronous operation (this is like calling a BeginXxx method)
            wc.DownloadStringAsync(new Uri("http://Wintellect.com"));

.net有很多的类是这个模式

System.ComponentModel.Component-derived types 

System.ComponentModel.BackgroundWorker

System.Media.SoundPlayer

System.Net.WebClient

System.Net.NetworkInformation.Ping

System.Windows.Forms.PictureBox (derived from Control)

System.Object-derived types

System.Net.Mail.SmtpClient

System.Deployment.Application.ApplicationDeployment

System.Deployment.Application.InPlaceHostingManager

System.Activities.WorkflowInvoker

System.ServiceModel.Activities.WorkflowControlClient

System.Net.PeerToPeer.PeerNameResolver

System.Net.PeerToPeer.Collaboration.ContactManager

System.Net.PeerToPeer.Collaboration.Peer

System.Net.PeerToPeer.Collaboration.PeerContact

System.Net.PeerToPeer.Collaboration.PeerNearMe

System.ServiceModel.Discovery.AnnouncementClient

System.ServiceModel.Discovery.DiscoveryClient

使用TaskCompletionSource将EAP转换为Task

            // The System.Net.WebClient class supports the Event-based Asynchronous Pattern
            WebClient wc = new WebClient();

            // Create the TaskCompletionSource and its underlying Task object
            var tcs = new TaskCompletionSource<String>();

            // When a string completes downloading, the WebClient object raises the 
            // DownloadStringCompleted event which will invoke our ProcessString method
            wc.DownloadStringCompleted += (sender, ea) =>
            {
                // This code always executes on the GUI thread; set the Task’s state
                if (ea.Cancelled) tcs.SetCanceled();
                else if (ea.Error != null) tcs.SetException(ea.Error);
                else tcs.SetResult(ea.Result);
            };

            // Have the Task continue with this Task that shows the result in a message box
            // NOTE: The TaskContinuationOptions.ExecuteSynchronously flag is required to have this code
            // run on the GUI thread; without the flag, the code runs on a thread pool thread 
            tcs.Task.ContinueWith(t =>
            {
                try
                {
                    System.Windows.Forms.MessageBox.Show(t.Result);
                }
                catch (AggregateException ae)
                {
                    System.Windows.Forms.MessageBox.Show(ae.GetBaseException().Message);
                }
            }, TaskContinuationOptions.ExecuteSynchronously);

            // Start the asynchronous operation (this is like calling a BeginXxx method)
            wc.DownloadStringAsync(new Uri("http://Wintellect.com"));

APM之EAP APM比较、

 

优点

缺点

EAP

可以和Visual Stuido配合使用,提供设计时支持

EAP是通过SynchronizationContext处理线程模型的,因此GUI程序中使用方便

比APM消耗的更多地内存、更慢的速度

EAP的异常不会抛出

APM

APM更接近事物本质

EAP内部一般都是用APM事先

-

详细参考:

Clr Via C#

http://transbot.blog.163.com

http://ys-f.ys168.com/?CLR_via_CSharp_3rd_Edition_Code_by_Jeffrey_Richter.zip_55bism1e0e7bkisjthit2bso0cm5bs4bs1b5bktnql0c0bu22f05f12z

posted @   2012  阅读(1065)  评论(1编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2010-05-11 arcgis开发笔记【DeepZoom应用】
点击右上角即可分享
微信分享提示