WhenAny with a List of Different Types of Task, Processing Each as They Finish
I have published two previous posts on this topic, one here, and another here, and then there was a very interesting Twitter chat here, and this post is in response to that.
Here is a way to start multiple Tasks<T>
where T
is different in each, WhenAny
the list, processing the first to finish, then second, then the third, and so on.
The code is fairly straightforward, so I’m not going to give an explanation beyond saying pattern matching has been replaced with a simple result ==
(again suggested by Andrew Lock).
public class Program
{
public static async Task Main()
{
Task<int> getIntTask = GetIntAsync();
Task<string> getStringTask = GetStringAsync();
Task<char> getCharTask = GetCharAsync();
List<Task> tasks = new List<Task> {getIntTask, getStringTask, getCharTask};
while(tasks.Any())
{
var result = await Task.WhenAny(tasks);
if (result == getIntTask)
{
int value = await getIntTask;
Console.WriteLine($"GetIntAsync completed : {value}");
}
else if (result == getStringTask)
{
string value = await getStringTask;
Console.WriteLine($"GetStringAsync completed: {value}");
}
else if (result == getCharTask)
{
char value = await getCharTask;
Console.WriteLine($"GetCharTask completed: {value}");
}
tasks.Remove(result);
}
}
public static async Task<int> GetIntAsync()
{
await Task.Delay(random.Next(100, 500));
return 123;
}
public static async Task<string> GetStringAsync()
{
await Task.Delay(random.Next(100, 500));
return "123456789";
}
public static async Task<char> GetCharAsync()
{
await Task.Delay(random.Next(100, 500));
return '9';
}
static Random random = new Random();
}