I have an application that pulls a fair amount of data from different sources. A local database, a networked database, and a web query. Any of these can take a few seconds to complete. So, first I decided to run these in parallel:
Parallel.Invoke(
() => dataX = loadX(),
() => dataY = loadY(),
() => dataZ = loadZ()
);
As expected, all three execute in parallel, but execution on the whole block doesn't come back until the last one is done.
Next, I decided to add a spinner or "busy indicator" to the application. I don't want to block the UI thread or the spinner won't spin. So these need to be ran in async
mode. But if I run all three in an async mode, then they in affect happen "synchronously", just not in the same thread as the UI. I still want them ran parallel.
spinner.IsBusy = true;
Parallel.Invoke(
async () => dataX = await Task.Run(() => { return loadX(); }),
async () => dataY = await Task.Run(() => { return loadY(); }),
async () => dataZ = await Task.Run(() => { return loadZ(); })
);
spinner.isBusy = false;
Now, the Parallel.Invoke does not wait for the methods to finish and the spinner is instantly off. Worse, dataX/Y/Z are null and exceptions occur later.
What's the proper way here? Should I use a BackgroundWorker instead? I was hoping to make use of the .Net 4.5 features.
It sounds like you really want something like:
That way you're asynchronously waiting for all the tasks to complete (
Task.WhenAll
returns a task which completes when all the other tasks complete), without blocking the UI thread... whereasParallel.Invoke
(andParallel.ForEach
etc) are blocking calls, and shouldn't be used in the UI thread.(The reason that
Parallel.Invoke
wasn't blocking with your async lambdas is that it was just waiting until eachAction
returned... which was basically when it hit the start of the await. Normally you'd want to assign an async lambda toFunc<Task>
or similar, in the same way that you don't want to writeasync void
methods usually.)As you stated in your question, two of your methods query a database (one via sql, the other via azure) and the third triggers a POST request to a web service. All three of those methods are doing I/O bound work.
What happeneds when you invoke
Parallel.Invoke
is you basically trigger three ThreadPool threads to block and wait for I/O based operations to complete, which is pretty much a waste of resources, and will scale pretty badly if you ever need to.Instead, you could use async apis which all three of them expose:
HttpClient.PostAsync
Lets assume the following methods:
You can call them like this:
This will have the same desired outcome. It wont freeze your UI, and it would let you save valuable resources.