Created
July 10, 2018 08:22
-
-
Save JimBobSquarePants/ec7e267b797451271747efd87b5e80ac to your computer and use it in GitHub Desktop.
Attempt at demoing returning only completed tasks from a collection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace TaskTest | |
{ | |
class Program | |
{ | |
private static Random r = new Random(); | |
static async Task Main(string[] args) | |
{ | |
var tasks = new Task<IEnumerable<int>>[] { ExternalTask(), ExternalTask(), ExternalTask(), ExternalTask(), ExternalTask() }; | |
var t2 = await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(3000)); | |
var completedResults = tasks | |
.Where(t => t.Status == TaskStatus.RanToCompletion) | |
.Select(t => t.Result) | |
.ToList(); | |
foreach (var item in completedResults) | |
{ | |
Console.WriteLine($"Task completed with {item.First()} delay."); | |
} | |
Console.ReadLine(); | |
} | |
private static Task<IEnumerable<int>> ExternalTask() | |
{ | |
int delay = r.Next(0, 6000); | |
Task.Delay(delay); | |
var enumerable = Enumerable.Repeat(delay, 6); | |
return Task.FromResult(enumerable); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Complete working demo.
await
all the things!