I am newbie in using of await/async and windows phone 8.1 programming. I need to run async method simulateously in more than one thread. May be four, because my phone has four cores. But i cannot figure it out :-(
This is example of my async method.
public async Task GetFilesAsyncExample(StorageFolder root)
{
IReadOnlyList<StorageFolder> folders = await root.GetFoldersAsync();
//DO SOME WORK WITH FOLDERS//
}
Four threads can be ensured by using of a semaphore object, but how i can run it in simulatously running threads?
EDIT: This is my code which explores folder structure and log metadata about files into database. I want to speed up execution of this code by calling method "async LogFilesFromFolderToDB(StorageFolder folder)" simulateously in separate thread for each 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]);
}
Method: async LogFilesFromFolderToDB(StorageFolder folder) looks like:
async Task LogFilesFromFolderToDB(StorageFolder folder)
{
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
//SOME ANOTHER CODE//
}
Parallel.Foreach can help to resolve this issue.
Try the below code,
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//
}