我正在为Windows设备开发通用Windows应用程序。我正在开发的应用程序在c++/CX。
在应用程序中,我想检查设备上是否存在文件,并且呼叫应该是阻塞呼叫。因此,我编写了如下所示的函数:
FileExist(String^ myFolder, String ^myFile)
{
// Get the folder object that corresponds to myFolder
// this absolute path in the file system.
try{
create_task(StorageFolder::GetFolderFromPathAsync(myFolder)).then([=] (StorageFolder^ folder){
create_task(folder->GetFileAsync(name)).then([=](StorageFile^ myfile){
return true;
});
return false;
});
}
catch (Exception^ e)
{
return false;
}
}
但是GetFolderFromPathAsync和GetFileAsync调用是异步调用,我的函数应该阻塞,所以我把等待每个这些lambda。但我得到以下错误。
"一个无效参数被传递给一个函数,该函数认为无效参数是致命的。"
所以谁能告诉我如何阻塞调用通用Windows应用程序的文件存在
如果你的方法在UI线程上运行-你不能让它阻塞,因为它使用异步api,这会阻止异步调用返回结果,导致死锁。如果运行"基于任务的延续",你可以使用阻塞get()方法来等待和获取任务的结果。
"在Windows Store应用中,不要在STA上运行的代码中调用wait。否则,运行时抛出concurrency::invalid_operation,因为该方法阻塞了当前线程,并可能导致应用程序变得无响应。但是,您可以调用concurrency::task::get方法来接收基于任务的延续中的前一个任务的结果。"
https://msdn.microsoft.com/en-us/library/hh749955.aspx