【发布时间】: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->GetResults();时,我遇到了内存访问冲突
我在这里缺少什么?我来自 c# 背景,在其中这真的很容易做:/
我尝试使用 '.then' 而不是注册事件,但我什至无法编译这些事件。
感谢您的帮助!
【问题讨论】:
-
我还没有机会查看您的代码,但作为同步替代方案,请考虑 CopyFile2,它可以从 Windows 应用商店应用程序调用。
-
是的,看起来好多了:)
-
这个链接解释了使用 C++ 的异步编程模型:msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx
-
尝试将要在 lambda 中捕获的变量中的
this替换为=。但是=只会捕获那些在 lambda 范围内的变量。如果变量m_installFolder、m_localFolder和m_dbName与 lambda 处于相同的范围内,则可以。如果没有,请在方括号之间明确提及。
标签: c++ windows-runtime c++-cx