启动链任务在C#中等待所有结果

时间:2017-06-14 07:17:08

标签: c# .net async-await task

我需要启动 Tasks并等待所有这些结果。

List<int> myAsyncWork1()
List<int> myAsyncWork2()
List<int> myAsyncWork3()

var tasks = new Func<Task>[]
{
   () => myAsyncWork1(),
   () => myAsyncWork2(),
   () => myAsyncWork3()
};

await Task.WhenAll(tasks.Select(task => task()).ToArray()); //Async    

当所有List<int> 完成时,我们如何获得Tasks所有方法?

3 个答案:

答案 0 :(得分:3)

您可以简单地使用fs的结果,例如:

WhenAll

答案 1 :(得分:2)

确定完成所有任务后,您可以使用task.Result属性。

var tasksFunc = new Func<Task<List<int>>>[]
{
   () => myAsyncWork1(),
   () => myAsyncWork2(),
   () => myAsyncWork3()
};

var tasks = tasksFunc.Select(func => func());
await Task.WhenAll(tasks);

var allLists = tasks.Select(task => task.Result);  

答案 2 :(得分:-1)

    private static void Main(string[] args)
    {
        var tasks = new List<Task<List<int>>>(){
            myAsyncWork1(),
            myAsyncWork2(),
            myAsyncWork3()
        };            

        var results = Task.WhenAll(tasks).Result;
        var numbers = results.SelectMany(x => x).ToList();
        Console.WriteLine(string.Join(" ", numbers.Select(x => x.ToString())));            
        Console.ReadKey();
    }

    static Task<List<int>> myAsyncWork1()
    {            
        return Task.Factory.StartNew(() =>
        {
            Console.WriteLine("MyAsyncWork1 started!");
            Thread.Sleep(300);
            Console.WriteLine("MyAsyncWork1 finished!");
            return new List<int>() { 1, 2, 3 };
        });
    }
    static Task<List<int>> myAsyncWork2()
    {
        return Task.Factory.StartNew(() =>
        {
            Console.WriteLine("MyAsyncWork2 started!");
            Thread.Sleep(200);
            Console.WriteLine("MyAsyncWork2 finished!");
            return new List<int>() { 4, 5, 6 };
        }); ;
    }
    static Task<List<int>> myAsyncWork3()
    {
        return Task.Factory.StartNew(() =>
        {
            Console.WriteLine("MyAsyncWork3 started!");
            Thread.Sleep(200);
            Console.WriteLine("MyAsyncWork3 finished!");
            return new List<int>() { 7, 8, 9 };
        });
    }