WhenAny with Two Different Types of Task and Waiting for Both to Finish

A little while ago I published a post where I show how to use WhenAny with different types of task. In that, I was only interested in the first task that finished.

But I was asked on Twitter how you wait for the first, process it, then wait for the second, and process it.

Here is a solution that works, I don’t know if the gods of async programming would be happy though. User beware.

using System;
using System.Threading.Tasks;
                    
public class Program
{
    public static async Task Main()
    {
        Task<int> getIntTask = GetIntAsync();
        Task<string> getStringTask = GetStringAsync();

        List<Task> tasks = new List<Task> {getIntTask, getStringTask};

        var result = await Task.WhenAny(tasks);

        while(tasks.Any())
        {
            if (result is Task<int> intTask)
            {
                int value = await intTask;
                Console.WriteLine($"GetIntAsync completed : {value}");
            }
            else if (result is Task<string> stringTask)
            {
                string value = await stringTask;
                Console.WriteLine($"GetStringAsync completed: {value}");
            }  
            
            tasks.Remove(result);
            if (!tasks.Any())
            {
                break;
            }
            result = await Task.WhenAny(tasks);
        }
    }  

    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";
    }
    static Random random = new Random();
}
comments powered by Disqus

Related