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

时间:2016-02-18 11:34:33

标签: c# multithreading asynchronous windows-phone-8.1 windows-rt

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

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

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

使用信号量对象可以确保四个线程,但我如何在同时运行的线程中运行它?

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

 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]);
            }

方法:async LogFilesFromFolderToDB(StorageFolder文件夹)如下所示:

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

1 个答案:

答案 0 :(得分:1)

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//
    }