Example #1
0
 /// <summary>
 /// Executes a parallel For loop.
 /// </summary>
 /// <param name="start">Loop start index.</param>
 /// <param name="stop">Loop stop index.</param>
 /// <param name="loopBody">Loop body.</param>
 /// <remarks>The method is used to parallelise for loop by running iterations across
 /// several threads.
 /// Example usage:
 /// <code>
 /// for ( int i = 0; i &lt; 10; i++ )
 /// {
 ///   System.Diagnostics.Debug.WriteLine( "i = " + i );
 /// }
 /// </code>
 /// can be replaced by:
 /// <code>
 /// Parallel.For( 0, 10, delegate( int i )
 /// {
 ///   System.Diagnostics.Debug.WriteLine( "i = " + i );
 /// } );
 /// </code>
 /// If <c>Parallel.ThreadCount</c> is exactly <c>1</c>, no threads are spawned.
 /// </remarks>
 public static void For(int start, int stop, ParallelFor.ForLoopDelegate loopBody)
 {
     if (Parallel.threadCount == 1)
     {
         for (int i = start; i < stop; i++)
         {
             loopBody(i);
         }
     }
     else
     {
         lock (lockObject) {
             ParallelFor parallel = ParallelFor.GetInstance(threadCount);
             parallel.DoFor(start, stop, loopBody);
         }
     }
 }
Example #2
0
 /// <summary>
 /// Executes a parallel For loop.
 /// </summary>
 /// <param name="start">Loop start index.</param>
 /// <param name="stop">Loop stop index.</param>
 /// <param name="loopBody">Loop body.</param>
 /// <param name="cancellationToken">Used to signal if the user wishes to cancel the loop before it completes.</param>
 /// <remarks>The method is used to parallelise for loop by running iterations across
 /// several threads.
 /// Example usage:
 /// <code>
 /// for ( int i = 0; i &lt; 10; i++ )
 /// {
 ///   System.Diagnostics.Debug.WriteLine( "i = " + i );
 /// }
 /// </code>
 /// can be replaced by:
 /// <code>
 /// Parallel.For( 0, 10, delegate( int i )
 /// {
 ///   System.Diagnostics.Debug.WriteLine( "i = " + i );
 /// } );
 /// </code>
 /// If <c>Parallel.ThreadCount</c> is exactly <c>1</c>, no threads are spawned.
 /// </remarks>
 public static void For(int start, int stop, [NotNull, InstantHandle] Action <int> loopBody, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (loopBody == null)
     {
         throw new ArgumentNullException("loopBody");
     }
     if (Parallel.threadCount == 1)
     {
         for (int i = start; i < stop; i++)
         {
             loopBody(i);
             cancellationToken.ThrowIfCancellationRequested();
         }
     }
     else
     {
         lock (lockObject)
         {
             ParallelFor parallel = ParallelFor.GetInstance(threadCount);
             parallel.DoFor(start, stop, loopBody, cancellationToken);
             cancellationToken.ThrowIfCancellationRequested();
         }
     }
 }