C ++ / CX Metro Windows - create_task实现可防止使用未在该范围内定义的变量

时间:2014-07-09 23:16:22

标签: windows microsoft-metro c++-cx ppl

我试图在create_task的实现之外定义Uri ^。在java中,如果你有一个异步任务,添加final修饰符将允许你在异步代码中使用该变量(带有final修饰符)。

如何在异步代码中使用以下代码中的Uri ^ source?

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

1 个答案:

答案 0 :(得分:2)

只需捕获lambda中的变量 source ,就可以在任务的lambda主体中访问它:

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

}