无限等待将远程图像加载到后台代理中的BitmapImage()中

时间:2013-12-21 20:22:51

标签: windows-phone-8

我有一个远程JPEG的有效网址,我正在尝试在后台加载。但是我发现在调用BitmapImage()构造函数后我永远无法控制回来。我的问题是,如果这种方法有用,或者我应该把它全部放在一边,从NuGet加载BcpAsync项目并开始使用WebClient异步方法?

失败的示例网址是

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...          
    }

1 个答案:

答案 0 :(得分:1)

你需要调用CompletionTask.SetResult();将控制权返回给调用者方法。

这样可行(我在成功下载时返回100,因为您将任务设置为返回double)。

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);
}