Search code examples
windowsmicrosoft-metroc++-cxppl

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

Solution

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