0

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?

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there anything dangerous about updating UI components via dependency properties just using Task.Run? That works perfectly as well...
+1. @Nicros - no, just use normal InvokeRequired/Invoke (or whatever matching methods in framework you are using) as you would do in any other multi-threaded updates of UI elements.
Better yet, do whatever you need to do inside the async part and output the result as the result of the task. Then you await the task and use the result to update the UI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.