private async void btn_D_Cancel_Click(object sender, RoutedEventArgs e) { try { MessageDialog md = new MessageDialog("确定要取消任务吗?\r\n关联的分段任务也会被取消"); md.Commands.Add(new UICommand("确定") { Id = 0 }); md.Commands.Add(new UICommand("取消") { Id = 1 }); if (Convert.ToInt32((await md.ShowAsync()).Id) == 0) { var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); var data = (sender as Button).DataContext as DisplayModel; var item = ls.First(x => x.Guid.ToString() == data.guid); item.AttachAsync().Cancel(); var d = SqlHelper.GetDownload(data.guid); await DownloadHelper2.DeleteFolder(d.aid, d.cid, d.mode); } LoadDowning(); } catch (Exception) { } }
public async Task <IReadOnlyList <DownloadOperation> > DiscoverBackgroundDownloadsAsync() { var currentDownloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_transferGroup); _cancellationTokenSources.Clear(); foreach (var downloadOperation in currentDownloads) { //if (downloadOperation.Progress.Status != BackgroundTransferStatus.Running) continue; try { Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadOperationProgress); CancellationTokenSource cts = new CancellationTokenSource(); var attachTask = downloadOperation.AttachAsync().AsTask(cts.Token, progressCallback); var addCancelationTokenTask = attachTask.ContinueWith(antecedent => { if (antecedent.Status == TaskStatus.Faulted) { // Attaching to DownloadOperation has failed return; } _cancellationTokenSources.Add(antecedent.Result.Guid, cts); }); } catch { } } return(currentDownloads); }
public static async void UpdateDowningStatus() { try { bool use = SettingHelper.Get_Use4GDown(); var downloading = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); if (downloading.Count == 0) { return; } foreach (var item in downloading) { if (use) { item.CostPolicy = BackgroundTransferCostPolicy.Always; } else { item.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private async Task InitializeOperations() { try { _sync.WaitOne(); IReadOnlyList <DownloadOperation> list = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_group).AsTask(); foreach (var operation in list) { Operation oper = new Operation(); oper.operation = operation; _operations.Add(operation.RequestedUri, oper); } foreach (var oper in _operations.Values) { if (oper.operation.Progress.Status != BackgroundTransferStatus.Completed) { StartDownload(oper, true, true); } } } finally { _sync.Release(); } }
public static async Task <ObservableCollection <DownloadModel> > GetDownload(DownloadType type) { var group = ""; switch (type) { case DownloadType.song: group = "song"; break; case DownloadType.mv: group = "mv"; break; case DownloadType.other: group = "other"; break; default: break; } var downs = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(BackgroundTransferGroup.CreateGroup(group)); var downlist = new ObservableCollection <DownloadModel>(); if (downs.Count > 0) { foreach (var down in downs) { var model = new DownloadModel(); downlist.Add(model); } } return(downlist); }
//跳转,开始监视,需要判断是否已经监视,否则会出现N个通知 protected override async void OnNavigatedTo(NavigationEventArgs e) { bg.Color = ((SolidColorBrush)this.Frame.Tag).Color; if (e.Parameter != null) { pivot.SelectedIndex = (int)e.Parameter; } try { if (settings.SettingContains("HoldLight")) { tw_Light.IsChecked = (bool)settings.GetSettingValue("HoldLight"); } else { tw_Light.IsChecked = false; } list_Downing.Items.Clear(); downlingModel.Clear(); IReadOnlyList <DownloadOperation> downloads = null; GetDownOk(); GetDownOk_New(); // 获取所有后台下载任务 downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadManage.DownModel.group); if (downloads.Count > 0) { foreach (var item in downloads) { //ls.Add(item.Guid); list_Downing.Items.Add(new DownloadManage.HandleModel() { downOp = item, Size = item.Progress.BytesReceived.ToString(), downModel = await GetInfo(item.Guid.ToString()) }); } //list.ItemsSource = downlingModel; } if (downloads.Count > 0) { List <Task> tasks = new List <Task>(); foreach (DownloadManage.HandleModel model in list_Downing.Items) { //bool test = HandleList.Contains(model.downOp.Guid.ToString()); if (!HandleList.Contains(model.downOp.Guid.ToString())) { // 监视指定的后台下载任务 HandleList.Add(model.downOp.Guid.ToString()); tasks.Add(HandleDownloadAsync(model)); } } await Task.WhenAll(tasks); } } catch (Exception) { } }
/// <summary> /// Найти все фоновые загрузки и обработать их. /// </summary> public async void DiscoverActiveDownloads() { lock (_lockObject) { if (_downloadsAttached) { return; } _downloadsAttached = true; } IsLoading = true; await Task.Run(async() => { IReadOnlyList <DownloadOperation> downloads = null; try { downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_transferGroup); } catch (Exception ex) { WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult); _logService.LogText($"Getting downloads error - {error}\n{ex.ToString()}"); } if (downloads != null && downloads.Count > 0) { for (int i = 0; i < downloads.Count; i++) { HandleDownloadAsync(downloads[i], false); } } }); IsLoading = false; }
// 加载指定组的下载任务 private async Task LoadDownloadAsync() { IReadOnlyList <DownloadOperation> downloads = null; try { // 获取指定组的下载任务 downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_group); } catch (Exception ex) { WriteLine(ex.ToString()); return; } if (downloads.Count > 0) { List <Task> tasks = new List <Task>(); foreach (DownloadOperation download in downloads) { // 监视指定的后台下载任务 tasks.Add(HandleDownloadAsync(download, false)); } await Task.WhenAll(tasks); } }
private async void btn_D_Cancel_Click(object sender, RoutedEventArgs e) { try { MessageDialog md = new MessageDialog("确定要取消任务吗?\r\n关联的分段任务也会被取消"); md.Commands.Add(new UICommand("确定") { Id = 0 }); md.Commands.Add(new UICommand("取消") { Id = 1 }); if (Convert.ToInt32((await md.ShowAsync()).Id) == 0) { var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); var data = (sender as Button).DataContext as DisplayModel; //var down_tasks = (list_Downing.ItemsSource as ObservableCollection<DisplayModel>).Where(x => x.cid == data.cid).ToList(); cts[data.cid].Cancel(); //foreach (var item in down_tasks) //{ // var task_item = ls.FirstOrDefault(x => x.Guid.ToString() == item.guid); // if (task_item.Progress.Status == BackgroundTransferStatus.Running) // { // task_item.Pause(); // } //} //await Task.Delay(1000); //for (int i = 0; i < down_tasks.Count; i++) //{ // var task_item = ls.FirstOrDefault(x => x.Guid.ToString() == down_tasks[0].guid); // if (task_item != null) // { // cts[task_item.Guid].Cancel(); // } // await Task.Delay(1000); //} using (var context = SqlHelper.CreateContext()) { var d = context.GetDownload(data.guid); await DownloadHelper2.DeleteFolder(d.Aid, d.Cid, d.Mode); } LoadDowning(); } } catch (Exception ex) { Debug.WriteLine(ex); } }
/// <summary> /// キャッシュダウンロードのタスクから /// ダウンロードの情報を復元します /// </summary> /// <returns></returns> private async Task RestoreBackgroundDownloadTask() { // TODO: ユーザーのログイン情報を更新してダウンロードを再開する必要がある? // ユーザー情報の有効期限が切れていた場合には最初からダウンロードし直す必要があるかもしれません var tasks = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_NicoCacheVideoBGTransferGroup); foreach (var task in tasks) { NicoVideoCacheProgress info = null; try { var _info = VideoCacheManager.CacheRequestInfoFromFileName(task.ResultFile); var nicoVideo = new NicoVideo(_info.RawVideoId, _HohoemaApp.ContentProvider, _HohoemaApp.NiconicoContext, _HohoemaApp.CacheManager); var session = await nicoVideo.CreateVideoStreamingSession(_info.Quality, forceDownload : true); if (session?.Quality == _info.Quality) { continue; } info = new NicoVideoCacheProgress(_info, task, session); await RestoreDonloadOperation(info, task); Debug.WriteLine($"実行中のキャッシュBGDLを補足: {info.RawVideoId} {info.Quality}"); } catch { Debug.WriteLine(task.ResultFile + "のキャッシュダウンロード操作を復元に失敗しました"); continue; } try { task.Resume(); } catch { if (task.Progress.Status != BackgroundTransferStatus.Running) { await RemoveDownloadOperation(info); // ダウンロード再開に失敗したらキャッシュリクエストに積み直します // 失敗の通知はここではなくバックグラウンドタスクの 後処理 として渡されるかもしれません DownloadProgress?.Invoke(this, info); } } } }
private async void btn_D_Download_Click(object sender, RoutedEventArgs e) { try { var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); var data = (sender as Button).DataContext as DisplayModel; var item = ls.First(x => x.Guid.ToString() == data.guid); item.Resume(); data.backgroundTransferStatus = item.Progress.Status; } catch (Exception) { } }
private async Task CancelActiveDownloadsAsync() { IReadOnlyList <DownloadOperation> downloads = null; try { // Note that we only enumerate transfers that belong to the transfer group used by this sample // scenario. We'll not enumerate transfers started by other sample scenarios in this app. downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(notificationsGroup); } catch (Exception ex) { if (!IsExceptionHandled("Discovery error", ex)) { throw; } return; } // If previous instances of this scenario started transfers that haven't completed yet, cancel them now // so that we can start this scenario cleanly. if (downloads.Count > 0) { CancellationTokenSource canceledToken = new CancellationTokenSource(); canceledToken.Cancel(); Task[] tasks = new Task[downloads.Count]; for (int i = 0; i < downloads.Count; i++) { tasks[i] = downloads[i].AttachAsync().AsTask(canceledToken.Token); } try { await Task.WhenAll(tasks); } catch (TaskCanceledException) { } Log(String.Format(CultureInfo.CurrentCulture, "Canceled {0} downloads from previous instances of this scenario.", downloads.Count)); } // After cleaning up downloads from previous scenarios, enable buttons to allow the user to run the sample. ToastNotificationButton.IsEnabled = true; TileNotificationButton.IsEnabled = true; }
private async void btn_PauseAll_Click(object sender, RoutedEventArgs e) { var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); foreach (var item in ls) { try { item.Pause(); } catch (Exception) { } } // LoadDowning(); }
private async void Btn_Resume_Items_Click(object sender, RoutedEventArgs e) { var data = (sender as Button).DataContext as DownloadDisplayInfo; var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); foreach (var item in ls.Where(x => data.items.Count(y => y.guid == x.Guid.ToString()) != 0)) { try { item.Resume(); } catch (Exception) { } } //LoadDowning(); }
public MediaCache(StorageFolder cache_directory, String token) { this.cache_directory = cache_directory; this.token = token; group = BackgroundTransferGroup.CreateGroup(token); client = new BackgroundDownloader(); client.TransferGroup = group; pending_downloads = new Dictionary <Uri, Task <StorageFile> >(); finished_downloads = new Dictionary <Uri, StorageFile>(); pending_metadata = new Dictionary <string, Task <string> >(); finished_metadata = new Dictionary <string, string>(); IReadOnlyList <DownloadOperation> downloads = Task.Run(async() => { try { return(await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(group)); } catch (Exception) { return(new List <DownloadOperation>()); } }).Result; foreach (var op in downloads) { try { var pending = fetchObjectToCache(op.RequestedUri, op); if (!pending.IsCompleted) { pending_downloads.Add(op.RequestedUri, pending); } } catch (Exception e) { Debug.WriteLine("Could not resume download to cache: " + e.ToString()); } } }
public static async Task <List <DownloadModel> > GetDownList() { try { if (DownFolder == null) { await GetfolderList(); } StorageFolder videoFolder = await DownFolder.CreateFolderAsync("GUID", CreationCollisionOption.OpenIfExists); List <DownloadModel> ls = new List <DownloadModel>(); var downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(group); if (downloads.Count > 0) { foreach (var item in downloads) { var file = await videoFolder.GetFileAsync(item.Guid.ToString() + ".json"); string filedata = await FileIO.ReadTextAsync(file); GuidModel m = JsonConvert.DeserializeObject <GuidModel>(filedata); StorageFile files = await StorageFile.GetFileFromPathAsync(m.path + @"\" + m.mid + ".json"); string json = await FileIO.ReadTextAsync(files); var dm = new DownloadModel(); dm.handel = new HandleModel(); dm.videoinfo = JsonConvert.DeserializeObject <VideoListModel>(json); dm.handel.downOp = item; dm.handel.Size = item.Progress.BytesReceived.ToString(); ls.Add(dm); } //list.ItemsSource = downlingModel; } return(ls); } catch (Exception) { return(new List <DownloadModel>()); } }
private async Task CancelActiveDownloadsAsync() { // Only the downloads that belong to the transfer group used by this sample scenario // will be canceled. IReadOnlyList <DownloadOperation> downloads = null; try { downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(reorderGroup); } catch (Exception ex) { if (!IsWebException("Discovery error", ex)) { throw; } return; } // If previous instances of this scenario started transfers that haven't completed yet, // cancel them now so that we can start this scenario cleanly. if (downloads.Count > 0) { CancellationTokenSource cancellationToken = new CancellationTokenSource(); cancellationToken.Cancel(); Task[] tasks = new Task[downloads.Count]; for (int i = 0; i < downloads.Count; i++) { tasks[i] = downloads[i].AttachAsync().AsTask(cancellationToken.Token); } // Cancel each download and ignore the cancellation exception. try { await Task.WhenAll(tasks); } catch (TaskCanceledException) { } } }
public async void UpdateSetting() { var downList = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper.group); var parallelDownload = SettingHelper.GetValue <bool>(SettingHelper.Download.PARALLEL_DOWNLOAD, true); var allowCostNetwork = SettingHelper.GetValue <bool>(SettingHelper.Download.ALLOW_COST_NETWORK, false); //设置下载模式 foreach (var item in downList) { if (parallelDownload) { item.TransferGroup.TransferBehavior = BackgroundTransferBehavior.Parallel; } else { item.TransferGroup.TransferBehavior = BackgroundTransferBehavior.Serialized; } item.CostPolicy = allowCostNetwork ? BackgroundTransferCostPolicy.Always : BackgroundTransferCostPolicy.UnrestrictedOnly; } }
private async void LoadDowning() { handelList.Clear(); ObservableCollection <DisplayModel> list = new ObservableCollection <DisplayModel>(); var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); foreach (var item in ls) { var data = SqlHelper.GetDownload(item.Guid.ToString()); handelList.Add(Handel(item)); list.Add(new DisplayModel() { title = data.title + " " + data.eptitle, backgroundTransferStatus = item.Progress.Status, index = (data.index + 1).ToString(), progress = GetProgress(item.Progress.BytesReceived, item.Progress.TotalBytesToReceive), guid = item.Guid.ToString(), size = GetSize(item.Progress.BytesReceived, item.Progress.TotalBytesToReceive), }); } list_Downing.ItemsSource = list; await Task.WhenAll(handelList); }
public async void DiscoverActiveDownloads() { IsLoading = true; IReadOnlyList <DownloadOperation> downloads = null; try { downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_transferGroup); } catch (Exception ex) { WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult); } if (downloads != null && downloads.Count > 0) { for (int i = 0; i < downloads.Count; i++) { HandleDownloadAsync(downloads[i], false); } } IsLoading = false; }
internal static Dictionary <string, BackgroundDownload> LoadDownloads() { var downloads = new Dictionary <string, BackgroundDownload>(); #if ENABLE_WINMD_SUPPORT CreateBackgroundDownloadGroup(); var downloadsTask = BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(s_BackgroundDownloadGroup).AsTask(); downloadsTask.Wait(); foreach (var download in downloadsTask.Result) { var uri = download.RequestedUri; var filePath = GetDownloadPath(download.ResultFile.Path); if (filePath != null) { var dl = new BackgroundDownloadUWP(uri, filePath); dl._download = download; switch (download.Progress.Status) { case BackgroundTransferStatus.Completed: dl._status = BackgroundDownloadStatus.Done; break; case BackgroundTransferStatus.Error: dl._status = BackgroundDownloadStatus.Failed; dl._error = download.CurrentWebErrorStatus.ToString(); break; } downloads[filePath] = dl; dl._downloadOperation = download.AttachAsync(); dl._downloadOperation.AsTask().ContinueWith(dl.DownloadTaskFinished, dl._cancelSource.Token); } } #endif return(downloads); }
/// <summary> /// 读取下载中 /// </summary> public async void LoadDownloading() { cts = new Dictionary <string, CancellationTokenSource>(); if (handelList == null) { handelList = new List <Task>(); } if (downloadOperations == null) { downloadOperations = new List <DownloadOperation>(); } ObservableCollection <DownloadingSubItem> subItems = new ObservableCollection <DownloadingSubItem>(); Downloadings.Clear(); var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper.group); foreach (var item in ls) { CancellationTokenSource cancellationTokenSource = null; var data = SettingHelper.GetValue <DownloadGUIDInfo>(item.Guid.ToString(), null); if (data == null || data.CID == null) { continue; } if (cts.ContainsKey(data.CID)) { cancellationTokenSource = cts[data.CID]; } else { cancellationTokenSource = new CancellationTokenSource(); cts.Add(data.CID, cancellationTokenSource); } if (!downloadOperations.Contains(item)) { downloadOperations.Add(item); handelList.Add(Handel(item, cancellationTokenSource)); } subItems.Add(new DownloadingSubItem() { ProgressBytes = item.Progress.BytesReceived, TotalBytes = item.Progress.TotalBytesToReceive, Progress = GetProgress(item.Progress.BytesReceived, item.Progress.TotalBytesToReceive), Status = item.Progress.Status, Title = data.Title, FileName = data.FileName, EpisodeTitle = data.EpisodeTitle, Path = data.Path, CID = data.CID, GUID = data.GUID, PauseItemCommand = PauseItemCommand, ResumeItemCommand = ResumeItemCommand }); } foreach (var item in subItems.GroupBy(x => x.CID)) { ObservableCollection <DownloadingSubItem> items = new ObservableCollection <DownloadingSubItem>(); foreach (var item2 in item) { items.Add(item2); } Downloadings.Add(new DownloadingItem() { EpisodeID = item.Key, Items = items, Title = item.FirstOrDefault().Title, EpisodeTitle = item.FirstOrDefault().EpisodeTitle, Path = item.FirstOrDefault().Path, DeleteItemCommand = DeleteItemCommand, }); } await Task.WhenAll(handelList); }
//跳转,开始监视,需要判断是否已经监视,否则会出现N个通知 protected override async void OnNavigatedTo(NavigationEventArgs e) { if (e.NavigationMode == NavigationMode.Back) { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; pivot.SelectedIndex = 1; } //messShow.Show("Tips:如果下载完成后应用不显示\r\n请点击已完成右下角的'导入已完成'", 5000); bg.Color = ((SolidColorBrush)this.Frame.Tag).Color; if (e.Parameter != null) { pivot.SelectedIndex = (int)e.Parameter; } try { if (settings.SettingContains("HoldLight")) { tw_Light.IsChecked = (bool)settings.GetSettingValue("HoldLight"); } else { tw_Light.IsChecked = false; } list_Downing.Items.Clear(); downlingModel.Clear(); IReadOnlyList <DownloadOperation> downloads = null; GetDownOk_New(); // 获取所有后台下载任务 downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadManage.DownModel.group); if (downloads.Count > 0) { foreach (var item in downloads) { //ls.Add(item.Guid); list_Downing.Items.Add(new DownloadManage.HandleModel() { downOp = item, Size = item.Progress.BytesReceived.ToString(), downModel = await GetInfo(item.Guid.ToString()) }); } //list.ItemsSource = downlingModel; } if (downloads.Count > 0) { List <Task> tasks = new List <Task>(); foreach (DownloadManage.HandleModel model in list_Downing.Items) { //bool test = HandleList.Contains(model.downOp.Guid.ToString()); if (!HandleList.Contains(model.downOp.Guid.ToString())) { // 监视指定的后台下载任务 HandleList.Add(model.downOp.Guid.ToString()); tasks.Add(HandleDownloadAsync(model)); } } await Task.WhenAll(tasks); } } catch (Exception) { } finally { if (list_Downing.Items.Count != 0) { txt_NoDown.Visibility = Visibility.Collapsed; } else { txt_NoDown.Visibility = Visibility.Visible; } } }
private async Task LoadDowning() { pr_loading.Visibility = Visibility.Visible; cts = new Dictionary <string, CancellationTokenSource>(); if (handelList == null) { handelList = new List <Task>(); } if (downloadOperations == null) { downloadOperations = new List <DownloadOperation>(); } downloadDisplayInfos = new ObservableCollection <DownloadDisplayInfo>(); List <DisplayModel> list = new List <DisplayModel>(); var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group); foreach (var item in ls) { CancellationTokenSource cancellationTokenSource = null; var data = SqlHelper.GetDownload(item.Guid.ToString()); if (cts.ContainsKey(data.cid)) { cancellationTokenSource = cts[data.cid]; } else { cancellationTokenSource = new CancellationTokenSource(); cts.Add(data.cid, cancellationTokenSource); } //cancellationTokenSource.Token.Register(Handel(item, cancellationTokenSource)); if (!downloadOperations.Contains(item)) { downloadOperations.Add(item); handelList.Add(Handel(item, cancellationTokenSource)); } list.Add(new DisplayModel() { cid = data.cid, title = data.title + " " + data.eptitle, backgroundTransferStatus = item.Progress.Status, index = (data.index + 1).ToString("00"), progress = GetProgress(item.Progress.BytesReceived, GetTotalBytesToReceive(item)), guid = item.Guid.ToString(), size = GetSize(item.Progress.BytesReceived, GetTotalBytesToReceive(item)), id = data.aid, mode = data.mode }); } foreach (var item in list.GroupBy(x => x.cid)) { ObservableCollection <DisplayModel> displays = new ObservableCollection <DisplayModel>(); foreach (var item2 in item.OrderBy(x => x.index)) { displays.Add(item2); } downloadDisplayInfos.Add(new DownloadDisplayInfo() { title = displays[0].title + " " + displays[0].eptitle, cid = item.Key, id = displays[0].id, mode = displays[0].mode, items = displays }); } listDown.ItemsSource = downloadDisplayInfos; downCount.Text = downloadDisplayInfos.Count.ToString(); //list_Downing.ItemsSource = list; pr_loading.Visibility = Visibility.Collapsed; await Task.WhenAll(handelList); }
// Just for debug private async void CommentButton_Click(object sender, RoutedEventArgs e) { var d = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(BackgroundTransferGroup.CreateGroup("Gallery")); var downloawwqwds = d.ToList(); }
public async Task <MediaSource> RequestMusic(MusicModel model) { EventHandler <DownloadOperation> downloadProgressHandler = (o, e) => { _logger.Debug($"Downloading status of {model.Title}:\n\t{e.Progress.Status}, ({e.Progress.BytesReceived}/{e.Progress.TotalBytesToReceive})"); switch (e.Progress.Status) { case BackgroundTransferStatus.Completed: _utilityHelper.RunAtUIThread(() => model.HasCached = true); break; default: break; } }; IRandomAccessStreamReference ras = null; DownloadOperation downloadOperation = null; var downloadProgress = new Progress <DownloadOperation>(); downloadProgress.ProgressChanged += downloadProgressHandler; var cacheFile = await _createMusicFile(model); if (cacheFile == null) { var operations = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_backgroundDownloaderGroup); foreach (var item in operations) { if (item.ResultFile is StorageFile cachedFile) { if (cachedFile.Name == _utilityHelper.CreateMd5HashString(model.Title)) { downloadOperation = item; break; } } } if (downloadOperation != null) { ras = downloadOperation.GetResultRandomAccessStreamReference(); downloadOperation.AttachAsync().AsTask(downloadProgress); } else { _logger.Warning($"Don't find the downloading task for {model.Title}"); return(null); } } else { downloadOperation = _backgroundDownloader.CreateDownload(model.Uri, cacheFile); downloadOperation.IsRandomAccessRequired = true; ras = downloadOperation.GetResultRandomAccessStreamReference(); downloadOperation.StartAsync().AsTask(downloadProgress); } var source = MediaSource.CreateFromStreamReference(ras, "audio/mpeg"); return(source); }