UWP BackgroundDownloader即使在PC上也会冻结

时间:2017-05-26 12:17:05

标签: c# download background uwp

string url = "http://any_urls";
    MediaPlayer player = new MediaPlayer();

    public MainPage()
    {
        InitializeComponent();

        Debug.WriteLine("Download started");
        var file = Download().Result; // <-- Here's where it stucks
        Debug.WriteLine("Download finished");

        player.Source = MediaSource.CreateFromStorageFile(file);
        player.Play();
    }

    private async Task<StorageFile> Download()
    {
        StorageFile destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
            "data.mp3", CreationCollisionOption.GenerateUniqueName);
        BackgroundDownloader downloader = new BackgroundDownloader();
        DownloadOperation download = downloader.CreateDownload(new Uri(url), destinationFile);
        await download.StartAsync();
        return destinationFile;
    }

我已经在PC和手机上进行了测试,他们都冻结了整个过程。任何人都可以解决这个问题,或者对此有什么好的替代方案吗?

1 个答案:

答案 0 :(得分:0)

  1. 忘了打电话&#34; AsTask&#34;开始下载的方法。
  2. 无法使用异步协同工具。

    public MainPage()
    {
        this.InitializeComponent();
    }
    
    private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("Download started");
        var file = await DownloadAsync();
        Debug.WriteLine("Download finished");
    
        player.Source = MediaSource.CreateFromStorageFile(file);
        player.Play();
    }
    
    private async Task<StorageFile> DownloadAsync()
    {
        StorageFile destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
            "data.mp3", CreationCollisionOption.GenerateUniqueName);
        BackgroundDownloader downloader = new BackgroundDownloader();
        DownloadOperation download = downloader.CreateDownload(new Uri(url), destinationFile);
        await download.StartAsync().AsTask();
        return destinationFile;
    }