I saw Jon Skeet give a talk a year or so ago where he showed a snippet of C# 5 that would take a list of Tasks and return them in the order they completed.
It made use of async/await and WhenAny and was quite beautiful but I can't for the life of me remember how it worked. Now I have need for it.
I'm hoping to figure out how to create a method with a signature similar to this..
Task<IEnumerable<T>> InOrderOfCompletion<T>(IEnumerable<T> tasks) where T : Task
And could be used as follows:
public async Task<int> DelayedInt(int i)
{
await Task.Delay(i*100);
return i;
}
[Test]
public async void Test()
{
Task<int>[] tasks = new[] {5, 7, 1, 3, 2, 6, 4}.Select(DelayedInt).ToArray();
IEnumerable<Task<int>> ordered = await InOrderOfCompletion(tasks);
Assert.That(ordered.Select(t => t.Result).ToArray(), Is.EqualTo(new [] {1,2,3,4,5,6,7}));
}
I've come up with the following but it doesn't feel as simple as I remember
async Task<IEnumerable<T>> InOrderOfCompletion<T>(IEnumerable<T> tasks) where T : Task
{
HashSet<Task> taskSet = new HashSet<Task>(tasks);
List<T> results = new List<T>();
while(taskSet.Count > 0)
{
T complete = (T) await Task.WhenAny(taskSet);
taskSet.Remove(complete);
results.Add(complete);
}
return results;
}
Do anyone remember know the snippet I'm referring to or how this can be improved upon?
They list everything that you have to do, with the most important tasks at the top of the list, and the least important tasks at the bottom. By keeping such a list, you make sure that your tasks are written down all in one place so you don't forget anything important.
Sort tasks by dateGo to the Gantt Chart. Click the arrow to the right of the Start or Finish column heading. Click Sort Earliest to Latest or Sort Latest to Earliest.
Go to the Project menu and click on Autofilter option. Click on the autofilter arrow next to the % complete column heading and uncheck 100% value. All the completed tasks will be hidden and only the tasks that are in progress will be displayed.
The sorting task is a simple procedure for collecting similarity data in which. each assessor groups together stimuli based on their perceived similarities. Sorting is based on categorization—a natural cognitive process routinely.
Jon Skeet, Stephen Toub, and I all have slightly different approaches. Mine is available via NuGet if you don't want to write your own.
Actually, the key is to avoid Task.WhenAny
because that will turn the algorithm from O(N) into O(N^2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With