【问题标题】:C++/CX Metro Windows - create_task implementation prevents using variable not defined in that scopeC++/CX Metro Windows - create_task 实现防止使用未在该范围内定义的变量
【发布时间】:2014-08-31 03:45:14
【问题描述】:

我试图在 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);
    });
}

【问题讨论】:

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


    【解决方案1】:

    只需在 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);
    });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2013-05-30
      相关资源
      最近更新 更多