示例#1
0
        public async Task <bool> Download()
        {
            if (IsDownloading)
            {
                return(true);
            }

            DownloadCancellation = new CancellationTokenSource();
            DownloadTask         = Task.Run(async() =>
            {
                IsDownloading = true;

                try
                {
                    using (var response = await HttpWebRequest.CreateHttp(MP3URL).GetResponseAsync().ConfigureAwait(false))
                    {
                        MaxLenght = response.ContentLength;
                        using (var stream = response.GetResponseStream())
                        {
                            MP3FileName = string.Format("{0}_{1}_{2}.mp3", ShowName, Date, StartTime);
                            Mp3File     = await(await MixDataHandler.instance.GetFolder()).CreateFileAsync(MP3FileName, CreationCollisionOption.OpenIfExists);

                            using (MP3Stream = await Mp3File.OpenStreamForWriteAsync())
                            {
                                DownloadUpdateCancellation = new CancellationTokenSource();
                                DownloadUpdateTask         = Task.Run(() => CheckDownloadStatus(), DownloadUpdateCancellation.Token);

                                await stream.CopyToAsync(MP3Stream, 4096, DownloadUpdateCancellation.Token);
                            }
                        }
                    }

                    Downloaded = true;
                    fileSize   = (int)MaxLenght / 1024 / 1024;
                    NotifyPropertyChanged("FileSizeText");
                }
                catch (Exception)
                {
                    Downloaded = false;
                }
                finally
                {
                    IsDownloading        = false;
                    DownloadCancellation = null;
                    DownloadUpdateCancellation.Cancel();
                    DownloadUpdateCancellation = null;
                    MP3Stream      = null;
                    TimeDownloaded = DateTime.Now;
                    NotifyPropertyChanged("DownloadedOn");
                    MixDataHandler.instance.UpdateMix(this);
                    MediaPlayerViewModel.instance.CheckIfBackgroundTaskIsRunning();
                }

                return(Downloaded);
            }, DownloadCancellation.Token);

            return(await DownloadTask);
        }