dinghao

记录成长点滴

 

silverlight 异步陷阱(一)不能Remove事件处理程序

Silverlight中许多操作都要去异步完成,但有时候会碰到多个异步操作需要按照一定顺序完成,事件是把异步操作转换成同步操作的一种方法。

lambda是操作事件的简洁方式,事件、lambda、同步组合在一起,就会产生事件处理程序不能移除的状况。看下面的代码:


代码
public void LoadChapter(string uri)
      {
          
//两个异步操作需要协调

          EventHandler handler 
= (s, e) =>
          {
              
if (this.PagedContentListView == null)
              {
                  BookContentService contentService 
= new BookContentService();
                  EventHandler loadContentHandler 
= (ss, args) =>
                  {
                     
//必须在外层执行完后执行

                  };
                  contentService.Loaded 
-= loadContentHandler;
                  contentService.Loaded 
+= loadContentHandler;
                  contentService.Load(UriGenratorFaced.GeneratBookContentUri(uri));
              }

              Chapter 
= service.BookChapter;
                        };
          service.Loaded 
-= handler;
          service.Loaded 
+= handler;       } 


两个事件处理程序嵌套,保证内层的loadContentHandler在外层handler执行后执行,使两个异步操作同步。

看代码逻辑应该能够正常运行,但是每执行一次LoadChapter方法,handler事件处理程序就会被注册一次,导致handler的执行次数加1。

问题的原因是由于内层嵌套的loadContentHandler ,导致service.Loaded -= handler,不能移除handler。

解决方法:问题找到了,解决方法可以有两种。

1、使事件处理程序只能注册一次

比如不使用lambda,在类的构造函数中执行事件处理程序。

使用lambda但是增加标记值,使事件只注册一次。

自定义事件注册方式等。

2、每次移除所有事件处理程序

参见:http://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control

posted on 2011-02-16 13:59  思无邪  阅读(1660)  评论(1编辑  收藏  举报

导航