Nicros
Nicros

Reputation: 5183

Async code implementation correctness

I have an application where I make a call like this:

myViewModel.ProcessDirectoryAsync(rootDirectoryInfo);

and in myViewModel:

public async ProcessDirectoryAsync(DirectoryInfo rootDirectoryInfo)
{
    await Task.Run(() => ProcessDirectory(rootDirectoryInfo));
}

public void ProcessDirectory(DirectoryInfo rootDirectoryInfo)
{
    // do work and update progress in UI with a bunch of data
}

The idea is that I want my ui to show multiple threads of work, each updating the UI with its progress and data independently.

This code works just fine.

But I wonder if it is not right. If I put an await (as recommended by resharper :) ) on this line:

await myViewModel.ProcessDirectoryAsync(rootDirectoryInfo);

Then I see the threads progress serially, rather than in parallel. Which is not what I want.

So first, is there something inherently evil in the way I've implemented this (which works), and if so what is the correct way?

Upvotes: 0

Views: 75

Answers (1)

ths
ths

Reputation: 2942

the indirection and async/await seem unneccessary. just call

Task.Run(() => myViewModel.ProcessDirectory(rootDirectoryInfo));

btw., you should always await an async, and async functions should return a Task, except in event handlers. but all of this unneccessary here.

Upvotes: 1

Related Questions