【问题标题】:UWP BackgroundDownloader freezes even on PCUWP BackgroundDownloader 即使在 PC 上也会冻结
【发布时间】:2017-05-26 12:17:04
【问题描述】:
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 和手机上都进行了测试,它们都冻结了整个过程。任何人都可以解决这个问题,或者有什么好的替代方法吗?

【问题讨论】:

    标签: c# download background uwp


    【解决方案1】:
    1. 开始下载时忘记调用“AsTask”方法。
    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;
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      相关资源
      最近更新 更多