Asynchronous Loading Text Files in Metro/C++/DirectX Apps
By just adding a simple modification to the existing ReadDataAsync function, we can load text files asynchronously:
inline Concurrency::task<Platform::String^> ReadStringAsync(Platform::String^ filename)
{
using namespace Windows::Storage;
using namespace Concurrency;
auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
task<StorageFile^> getFileTask(folder->GetFileAsync(filename));
auto readBufferTask = getFileTask.then([] (StorageFile^ f)
{
return FileIO::ReadBufferAsync(f);
});
auto byteArrayTask = readBufferTask.then([] (Streams::IBuffer^ b) -> Platform::String^
{
return Streams::DataReader::FromBuffer(b)->ReadString(b->Length);
});
return byteArrayTask;
}
You can load files using the following code (don’t forget it is asynchronous.
auto loadTextTask = ReadStringAsync(L"Assets\\Text.txt")
.then([this](Platform::String^ text)
{
m_text = text;
});Enjoy!
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





