user812954
user812954

Reputation: 4391

C++/CX Metro Windows - create_task implementation prevents using variable not defined in that scope

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);
    });
}

Upvotes: 0

Views: 316

Answers (1)

Raman Sharma
Raman Sharma

Reputation: 4571

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);
});

}

Upvotes: 2

Related Questions