0

I am trying to define Uri^ outside of the implementation of create_task. In java, if you have an asynchronous task adding the final modifier would allow you to use that variable (with final modifier) inside the asynchronous code.

How can I use Uri^ source from the below code inside the asynchronous code?

void addDownload(Uri^ source, StorageFolder^ destinationFolder, String^ fileName) {
    boolean requestUnconstrainedDownload = false;
    IAsyncOperation<StorageFile^>^ asyncOperationStorageFile = destinationFolder->CreateFileAsync(fileName, CreationCollisionOption::GenerateUniqueName);
    auto createStorageFileTask = create_task(asyncOperationStorageFile);
    createStorageFileTask.then([] (StorageFile^ destinationFile) {
        BackgroundDownloader^ downloader = ref new BackgroundDownloader();
        DownloadOperation^ downloadOperation = downloader->CreateDownload(source, destinationFile);
        downloadOperation->Priority = BackgroundTransferPriority::Default;
        HandleDownloadAsync(downloadOperation, true);
    });
}
Steve
  • 6,334
  • 4
  • 39
  • 67
user812954
  • 3,951
  • 3
  • 19
  • 18

1 Answers1

2

Just capture the variable source in the lambda so it can be accessed in the lambda body of the task:

void addDownload(Uri^ source, StorageFolder^ destinationFolder, String^ fileName) {

boolean requestUnconstrainedDownload = false;
IAsyncOperation<StorageFile^>^ asyncOperationStorageFile = destinationFolder->CreateFileAsync(fileName, CreationCollisionOption::GenerateUniqueName);
auto createStorageFileTask = create_task(asyncOperationStorageFile);
createStorageFileTask.then([source] (StorageFile^ destinationFile) {
    BackgroundDownloader^ downloader = ref new BackgroundDownloader();
    DownloadOperation^ downloadOperation = downloader->CreateDownload(source, destinationFile);
    downloadOperation->Priority = BackgroundTransferPriority::Default;
    HandleDownloadAsync(downloadOperation, true);
});

}
Raman Sharma
  • 4,551
  • 4
  • 34
  • 63