Simplest way to run three methods in parallel in C#

前端 未结 5 1343
一向
一向 2020-12-04 14:01

I have three methods that I call to do some number crunching that are as follows

results.LeftFront.CalcAi();  
results.RightFront.CalcAi();  
results.RearSus         


        
5条回答
  •  悲&欢浪女
    2020-12-04 14:44

    To run parallel methods which are independent of each other ThreadPool.QueueUserWorkItem can also be used. Here is the sample method-

    public static void ExecuteParallel(params Action[] tasks)
    {
        // Initialize the reset events to keep track of completed threads
        ManualResetEvent[] resetEvents = new ManualResetEvent[tasks.Length];
    
        // Launch each method in it's own thread
        for (int i = 0; i < tasks.Length; i++)
        {
            resetEvents[i] = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback((object index) =>
                {
                    int taskIndex = (int)index;
    
                    // Execute the method
                    tasks[taskIndex]();
    
                    // Tell the calling thread that we're done
                    resetEvents[taskIndex].Set();
                }), i);
        }
    
        // Wait for all threads to execute
        WaitHandle.WaitAll(resetEvents);
    }
    

    More detail about this function can be found here:
    http://newapputil.blogspot.in/2016/03/running-parallel-tasks-using.html

提交回复
热议问题