运行 如何在单独的线程中多次执行异步方法?

How run async method multiple times in separate threads?

我是 await/async 和 windows phone 8.1 编程的新手。我需要在多个线程中模拟 运行 异步方法。可能是四个,因为我的phone有四个核心。但我想不通:-(

这是我的异步方法的示例。

public async Task GetFilesAsyncExample(StorageFolder root)
{
        IReadOnlyList<StorageFolder> folders = await root.GetFoldersAsync(); 
        //DO SOME WORK WITH FOLDERS//
}

可以通过使用信号量对象来确保四个线程,但是我如何才能运行它同时运行宁线程?

编辑: 这是我的代码,用于探索文件夹结构并将有关文件的元数据记录到数据库中。我想通过在每个文件夹的单独线程中模拟调用方法 "async LogFilesFromFolderToDB(StorageFolder folder)" 来加快此代码的执行速度。

 Stack<StorageFolder> foldersStack = new Stack<StorageFolder>();
            foldersStack.Push(root);
            while (foldersStack.Count > 0)
            {
                StorageFolder currentFolder = foldersStack.Pop();
                await LogFilesFromFolderToDB(null, currentFolder);// Every call of this method can be done in  a separate thread.
                IReadOnlyList<StorageFolder> folders = await currentFolder.GetFoldersAsync();
                for (int i = 0; i < folders.Count; i++)
                    foldersStack.Push(folders[i]);
            }

方法:异步 LogFilesFromFolderToDB(StorageFolder 文件夹)看起来像:

   async Task LogFilesFromFolderToDB(StorageFolder folder)
    {
        IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
        //SOME ANOTHER CODE//
    }

Parallel.Foreach 可以帮助解决这个问题。

试试下面的代码,

 public async Task GetFilesAsyncExample(StorageFolder root)
    {
        IReadOnlyList<StorageFolder> folders = await root.GetFoldersAsync();

        Parallel.ForEach(folders, (currentFolder) =>
        {
            Console.WriteLine("folder name:" + currentFolder.Name + " Files count" + currentFolder.GetFiles().Count());
        });
        //DO SOME WORK WITH FOLDERS//
    }