2011-12-23 46 views
0

我有一個Dispatcher,我必須用它來更新我的位圖,但是返回行是在調度程序內部的代碼完成之前執行的,所以結果並不如預期。在Dispatcher.invoke方法返回後

如何在調度員完成後返回一個值?我不能離開調度員的回報。

下面是我的代碼:

public ObservableCollection<FavoriteStruct> LoadMobion() 
    { 
     List<FavoriteMobion> results; 
     using (FavoriteDataContext context = new FavoriteDataContext(connectionString)) 
     { 
      IQueryable<FavoriteMobion> query = from c in context.TbFavoriteMobion 
              select c; 
      results = query.ToList(); 
     } 
     ObservableCollection<FavoriteStruct> lstFavStr = new ObservableCollection<FavoriteStruct>(); 
     if (results != null) 
     { 
      Thread load = new Thread(new ThreadStart(() => 
      { 
       Deployment.Current.Dispatcher.BeginInvoke(() => 
       { 
        foreach (var rst in results) 
        { 
         BitmapImage bi; 
         bi = new BitmapImage(); 
         bi.UriSource = new Uri("../Images/default_avatar_small.jpg", UriKind.Relative); 
         lstFavStr.Add(new FavoriteStruct() 
         { 
          Opacity = 0.8f, 
          Status = "../Images/offline.png", 
          RealID = rst.RealID, 
          GroupType = rst.GroupType, 
          MsgStatus = rst.MsgStatus == "" ? "offline" : rst.Path, 
          Name = rst.Name, 
          Path = rst.Path == "" ? "" : rst.Path, 
          Phone = rst.Phone, 
          Picture = bi 
         }); 
        } 
       }); 
      })); 
      load.Start(); 
      load.Join(); 
     } 
     return lstFavStr; 
    } 

回答

1

要調用一個新的線程,而BeginInvoke也是異步的,你不能阻止return語句從當你想,如果你使用的線程執行。你應該考慮重新格式化你的代碼結構。我建議你分開你的UI更新代碼和你填充集合的代碼。從線程中取出集合。 你的方法應該加載和顯示數據,還是隻返回它?在獲得result後,我會停止,返回該值,並使用另一個方法或代碼塊來用該數據更新UI。簡單地分開這兩個任務。