Wrap Windows 8/WP8 StorageFile用于同步C++访问

Wrap Windows 8/WP8 StorageFile for synchronous C++ access

本文关键字:用于 同步 C++ 访问 StorageFile WP8 Windows Wrap      更新时间:2023-10-16

我需要一个C++包装类,它可以从Windows8/WP8存储文件中同步读取/写入/查找数据(http://msdn.microsoft.com/library/windows/apps/br227171):

class FileWrapper
{
public:
    FileWrapper(StorageFile^ file); // IRandomAccessStream or IInputStream 
                                    // are fine as input arguments too
    byte* readBytes(int bytesToRead, int &bytesGot);
    bool writeBytes(byte* data, int size);
    bool seek(int position);
}

数据应该在运行中从文件中读取。它不应该缓存在内存中,存储文件也不应该复制到应用程序的目录中,在那里它可以使用标准的fopen和ifstream函数。

我试图弄清楚如何做到这一点(包括Microsoft文件访问示例代码:http://code.msdn.microsoft.com/windowsapps/File-access-sample-d723e597)但我被每个操作的异步访问所困扰。有人暗示过如何做到这一点吗?或者是否有内置功能?

问候,

通常,您使用create_task()方法包装异步操作,然后可以通过调用task.get()来等待任务的执行完成,以实现同步性,但IIRC这对文件访问不起作用,因为操作可能会尝试在执行时所在的线程上返回,如果您阻塞该线程,则最终会出现死锁。我没有时间尝试,但如果你从另一个线程开始,你可以像这样在线程上等待完成,尽管它可能仍然死锁:

auto createTaskTask = create_task([]()
{
    return create_task(FileIO::ReadTextAsync(file));
}
auto readFileTask = createTaskTask.get();
try 
{ 
    String^ fileContent = readFileTask.get(); 
} 
catch(Exception^ ex) 
{ 
    ...
}