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

后端 未结 5 1852
死守一世寂寞
死守一世寂寞 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:21

    By far the easiest way to do this is to use Parallel.Invoke()

    IList cats;
    IList food;
    
    Parallel.Invoke
    (
        () => cats = GetAllTheCats(foo),
        () => food = GetAllTheFood(foo)
    );
    

    Parallel.Invoke() will wait for all the methods to return before it itself returns.

    More information here: http://msdn.microsoft.com/en-us/library/dd460705.aspx

    Note that Parallel.Invoke() handles scaling to the number of processors in your system, but that only really matters if you're starting more than just a couple of tasks.

提交回复
热议问题