0

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

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

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

1 回答 1

2

只需在 lambda 中捕获变量,以便可以在任务的 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);
});

}
于 2014-07-13T14:43:54.157 回答