How can I run both of these methods 'at the same time' in .NET 4.5?

后端 未结 5 1849
死守一世寂寞
死守一世寂寞 2020-12-02 09:48

I have a method which does 2 independent pieces of logic. I was hoping I can run them both at the same time .. and only continue afterwards when both those

5条回答
  •  半阙折子戏
    2020-12-02 10:28

    Adding to the other answers, you could do something like:

    public PewPew SomeMethod(Foo foo)
    {
        Task> catsTask = GetAllTheCatsAsync(foo);
        Task> foodTask = GetAllTheFoodAsync(foo);
    
        // wait for both tasks to complete
        Task.WaitAll(catsTask, foodTask);
    
        return new PewPew
        {
            Cats = catsTask.Result,
            Food = foodTask.Result
        };
    }
    
    public async Task> GetAllTheCatsAsync(Foo foo)
    {
        await Task.Delay(7000); // wait for a while
        return new List();
    }
    
    public async Task> GetAllTheFoodAsync(Foo foo)
    {
        await Task.Delay(5000); // wait for a while
        return new List();
    }
    

提交回复
热议问题