How to store the return values when calling multiple function in parallel

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
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);
}


//Sample use

ExecuteParallel (() =>
{
CalculateArea (),
CalculateDistance (),
CalculateTime ()
});

if all these functions CalculateArea (), CalculateDistance (), CalculateTime () return some data then how to store them?

if any exception occur in any function when they execute at parallel....what will happen ? other function will not execute ?

again tell me how to know all the function running parallel completed?

Continue reading...
 
Back
Top