Reputation: 10358
Here is my code which generates XmlNodes in async way and then inserts these nodes into main document - sequentially because it is fast process and I also may need to keep certain order.
There is about 15 nodes to import. How can I refactor this code so the code is more compact?
XmlNode soccerNode = null;
XmlNode basketbalNode = null;
XmlNode hockeyNode = null;
...
var tasks = new List<Task>
{
Task.Factory.StartNew(() => soccerNode = this.getSoccer()),
Task.Factory.StartNew(() => basketbalNode = this.getBasketball()),
Task.Factory.StartNew(() => hockeyNode = this.getHockey()),
...};
Task.WaitAll(tasks.ToArray());
AddToMainDocument(soccerNode);
AddToMainDocument(basketbalNode);
AddToMainDocument(hockeyNode);
...
Upvotes: 0
Views: 85
Reputation: 664
I'm guessing getSoccer, getBasketball and getHockey are properties since your code example did not have any method parenthesis? If they are methods then just add the missing parenthesis to the code below.
var soccerTask = Task.Run(() => getSoccer).ConfigureAwait(false);
var basketbalTask = Task.Run(() => getBasketball).ConfigureAwait(false);
var hockeyTask = Task.Run(() => getHockey).ConfigureAwait(false);
AddToMainDocument(await soccerTask);
AddToMainDocument(await basketbalTask);
AddToMainDocument(await hockeyTask);
All three jobs are executed asynchronously and then you await them in the order you need them.
Regarding how to make your code more compact, I would need to know more about it. The methods/properties, are they all within the same object? Should all of them always be called? You could use reflection to find all of your methods, have attributes on them to specify order and use that information to spin up tasks and await them in the right order.
But to be honest, if you know which methods needs to be called then just do it manually as in your example. If you have a dynamic object where methods are added/removed then you should probably use reflection to do the job, otherwise it's just an unnecessary overhead.
Upvotes: 2
Reputation: 3623
A think this might help:
var t1 = Task.Factory.StartNew(() => soccerNode = /*Do something */);
var t2 = Task.Factory.StartNew(() => basketbalNode = /*Do something */);
var tasks = new List<Task> { t1, t2 };
Task.WaitAll(tasks.ToArray());
AddToMainDocument(t1.Result);
AddToMainDocument(t2.Result);
We wait until they are all done then add to the main document.
Upvotes: 0