如何处理 BackgroundTransfer DownloadOperation C++/WinRT 中的进度

How handle progress in BackgroundTransfer DownloadOperation C++/WinRT

我尝试在 c++/WinRT Windows 10 UWP 应用程序中通过 BackgroundTransfer::BackgroundDownloader 处理下载文件的进度。

我昨天读了 10 遍文档: https://docs.microsoft.com/en-us/uwp/api/windows.foundation.iasyncoperationwithprogress-2.progress?view=winrt-19041#Windows_Foundation_IAsyncOperationWithProgress_2_Progress

但我无法正确实施:(

这是我的示例代码(文件下载很好,但是如果我输入 .Progress 函数,我会出错: Error C2280 'void *winrt::Windows::Foundation::IUnknown::operator new(size_t)': attempting to reference a deleted function NativeModuleSample

代码:

BackgroundTransfer::BackgroundDownloader downloader{ BackgroundTransfer::BackgroundDownloader() };
BackgroundTransfer::DownloadOperation download = downloader.CreateDownload(uri, destinationFile);
auto progress = download.StartAsync();

progress.Progress(Windows::Foundation::AsyncOperationProgressHandler<BackgroundTransfer::DownloadOperation, BackgroundTransfer::BackgroundDownloadProgress>(
    [=](Windows::Foundation::IAsyncOperationWithProgress<BackgroundTransfer::DownloadOperation, BackgroundTransfer::DownloadOperation> const sender, BackgroundTransfer::BackgroundDownloadProgress args) {
        int progress_calc = (int)(100 * ((double)args.BytesReceived / (double)args.TotalBytesToReceive));    
    }
));

通过BackgroundTransfer::BackroundDownloader处理下载文件的进度,可以参考GitHub中sample的Scenario1_Download。

根据有关下载的示例,您可以将代码 progress.Progress(…) 更改为:

progress.Progress(Windows::Foundation::AsyncOperationProgressHandler<Windows::Networking::BackgroundTransfer::DownloadOperation, Windows::Networking::BackgroundTransfer::DownloadOperation>(
    [=](Windows::Foundation::IAsyncOperationWithProgress<Windows::Networking::BackgroundTransfer::DownloadOperation, Windows::Networking::BackgroundTransfer::DownloadOperation> const sender, 
        Windows::Networking::BackgroundTransfer::DownloadOperation args) {
               
            BackgroundDownloadProgress currentProgress = args.Progress();

            UINT64 percent = 0;
            if (currentProgress.TotalBytesToReceive > 0)
            {
                percent =(INT64)((double)currentProgress.BytesReceived * 100 / (double)currentProgress.TotalBytesToReceive);
            }
    }
));