2013-12-21 40 views
1

我有一個有效的URL,用於嘗試在後臺加載的遠程JPEG。但是我發現在調用BitmapImage()構造函數之後我再也沒有得到控制權。我的問題是,如果這種方法起作用,或者我應該全力以赴,從NuGet加載BcpAsync項目並開始使用WebClient異步方法?無限等待將遠程圖像加載到後臺代理中的BitmapImage()中

爲它失敗的樣本網址是

http://image.weather.com/images/maps/current/garden_june_720x486.jpg 

它是有效的。 .UpdateAsync()參考它從AppViewModel.Instance,這裏沒有明確引用它。

這裏的後臺代理:

protected override async void OnInvoke(ScheduledTask task) 
     { 
      AppViewModel.LoadData(); 

       await AppViewModel.Instance.RemoteImageProxy.UpdateAsync(); 
       AppViewModel.Instance.ImageUrl = AppViewModel.Instance.RemoteImageProxy.LocalFileUri; 
       AppViewModel.Instance.UpdateCount++; 
       PinnedTile.Update(); 
      } 

      AppViewModel.SaveData(); 
#if DEBUG 
      ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(AppViewModel.Instance.BgAgentInterval)); 
#endif 

      NotifyComplete(); 
     } 

這裏的調用方法:

public Task<double> UpdateAsync() { 

     LastCheckedTime = DateTime.UtcNow; 

     CompletionTask = new TaskCompletionSource<double>(); 

     // Not usually called on UI thread, not worth optimizing for that case here. 
     Deployment.Current.Dispatcher.BeginInvoke(() => {  //todo determine whether System.Windows.Deployment.Dispatcher can be called from main app, or just bgAgent. 
      HelperImageControl = new Image(); 
      HelperImageControl.Loaded += im_Loaded; 
      HelperImageControl.ImageFailed += im_ImageFailed; 
      HelperImageControl.ImageOpened += im_ImageOpened; 
// breakpoint here 
      HelperImageControl.Source = new BitmapImage(SourceUri); 
// stepping over the function, control does not return here. Nor are any of the above events fired. 
     }); 

     return CompletionTask.Task;          // this will be completed in one of the subsequent control events...   
    } 
+0

您是否在輸出窗口中看到任何異常? –

回答

1

你需要調用CompletionTask.SetResult();將控制返回給調用方法。

這是有效的(如果下載成功,我將返回100,因爲您將任務設置爲返回雙精度)。

TaskCompletionSource<double> CompletionTask; 
public Task<double> UpdateAsync() 
{ 
    CompletionTask = new TaskCompletionSource<double>(); 

    Deployment.Current.Dispatcher.BeginInvoke(() => 
    {  
     var HelperImageControl = new Image(); 

     var bmp = new BitmapImage(); 
     bmp.ImageOpened += bmp_ImageOpened; 
     bmp.ImageFailed += bmp_ImageFailed; 
     bmp.CreateOptions = BitmapCreateOptions.None; 

     bmp.UriSource = new Uri("http://image.weather.com/images/maps/current/garden_june_720x486.jpg", UriKind.Absolute); 

     HelperImageControl.Source = bmp; 
    }); 

    return CompletionTask.Task;            
} 

void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e) 
{ 
    CompletionTask.SetException(e.ErrorException); 
} 

void bmp_ImageOpened(object sender, RoutedEventArgs e) 
{ 
    CompletionTask.SetResult(100); 
} 
+1

感謝您找到我真正的bug!我在Image上設置事件處理程序,而不是BitmapImage。爲什麼前者不開火是一個難題。 在任何情況下,我實際上調用.SetResult()(在我從示例中省略的一段代碼中)。 – BobHy