【问题标题】:C++/CX WinRT File CopyC++/CX WinRT 文件复制
【发布时间】:2014-08-25 13:36:15
【问题描述】:

WinRT Windows::Storage 命名空间的异步性让我非常痛苦。

我的头文件中有以下私有成员:

//Members for copying the SQLite db file
Platform::String^ m_dbName;
Windows::Storage::StorageFolder^ m_localFolder;
Windows::Storage::StorageFolder^ m_installFolder;
Windows::Storage::StorageFile^ m_dbFile;

我的实现文件中有以下代码块:

//Make sure the SQLite Database is in ms-appdata:///local/
m_dbName = L"DynamicSimulations.db";
m_localFolder = ApplicationData::Current->LocalFolder;
m_installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;

auto getLocalFileOp = m_localFolder->GetFileAsync(m_dbName);
getLocalFileOp->Completed = ref new AsyncOperationCompletedHandler<StorageFile^>([this](IAsyncOperation<StorageFile^>^ operation, AsyncStatus status)
{
    m_dbFile = operation->GetResults();

    if(m_dbFile == nullptr)
    {
        auto getInstalledFileOp = m_installFolder->GetFileAsync(m_dbName);
        getInstalledFileOp->Completed = ref new AsyncOperationCompletedHandler<StorageFile^>([this](IAsyncOperation<StorageFile^>^ operation, AsyncStatus status)
        {
            m_dbFile = operation->GetResults();
            m_dbFile->CopyAsync(m_localFolder, m_dbName);
        });
    }
});

当它到达m_dbFile = operation-&gt;GetResults();时,我遇到了内存访问冲突

我在这里缺少什么?我来自 c# 背景,在其中这真的很容易做:/

我尝试使用 '.then' 而不是注册事件,但我什至无法编译这些事件。

感谢您的帮助!

【问题讨论】:

  • 我还没有机会查看您的代码,但作为同步替代方案,请考虑 CopyFile2,它可以从 Windows 应用商店应用程序调用。
  • 是的,看起来好多了:)
  • 这个链接解释了使用 C++ 的异步编程模型:msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx
  • 尝试将要在 lambda 中捕获的变量中的 this 替换为 =。但是= 只会捕获那些在 lambda 范围内的变量。如果变量 m_installFolderm_localFolderm_dbName 与 lambda 处于相同的范围内,则可以。如果没有,请在方括号之间明确提及。

标签: c++ windows-runtime c++-cx


【解决方案1】:

如果您对 WinRT 解决方案感兴趣,这里是:

看来您要做的就是将数据库文件从安装位置复制到本地文件夹中。为此,以下代码就足够了:

//Make sure the SQLite Database is in ms-appdata:///local/
m_dbName = L"DynamicSimulations.db";
m_localFolder = ApplicationData::Current->LocalFolder;
m_installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;

create_task(m_installFolder->GetFileAsync(m_dbName)).then([this](StorageFile^ file)
{
    create_task(file->CopyAsync(m_localFolder, m_dbName)).then([this](StorageFile^ copiedFile)
    {
        // do something with copiedFile
    });
});

【讨论】:

    【解决方案2】:

    我以前试过这个东西。不要这样做:

    if(m_dbFile == nullptr)
    

    而是验证“status”的值。

    if(status == AsyncStatus::Error)
    

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 2012-05-21
      相关资源
      最近更新 更多