Recursively enumerate files/folders using continuation tasks


  • I'm trying to use the asynchronous file functions to recursively list all files and folders within a given directory.  It works (in that it finds all folders and files), but the output order is a mess - I'll get a list of some folders, followed by a few files, followed by another folder, followed by the rest of the files which should have been listed before.  From this I surmise that my tasks aren't continuing on from each other in order as intended.  Any idea where I'm going wrong?

    void EnumerateFilesRecursively() { // Add a single root folder auto SourceFolders = ref new Platform::Collections::Vector<StorageFolder^>; SourceFolders->Append(KnownFolders::DocumentsLibrary); // Call recursive function to list all files/folders BuildFileList(SourceFolders->GetView()); } void BuildFileList(IVectorView<StorageFolder^>^ folders) { // For each folder we've been given std::for_each(begin(folders), end(folders), [this](StorageFolder^ folder) { // Add the folder name to the output string OutputText += folder->DisplayName + "\\\n"; // Create a task to find all subfolders create_task(folder->GetFoldersAsync()).then([this, folder](IVectorView<StorageFolder^>^ folders) ->IAsyncOperation<IVectorView<StorageFile^>^>^ { // Recurse to the next level for each folder BuildFileList(folders); return folder->GetFilesAsync(); }, task_continuation_context::use_current()).then(([this, folder](IVectorView<StorageFile^>^ files) { // Now list all files within this folder std::for_each(begin(files), end(files), [this](StorageFile^ file) { OutputText += file->Name + "\n"; }); }), task_continuation_context::use_current()); }); }

    BTW I might have been programming in standard C++ for too long, but I find this chaining of asynchronous tasks to perform an essentially linear task hard work (and goodbye to cross platform methods).  It would make so much more sense to kick off one asynchronous task, and do everything synchronously within it, wouldn't it?

    Thursday, November 15, 2012 4:50 PM


All replies