Advertisement
uniblab

poor man's way of limiting concurrency with PTL

Apr 10th, 2020
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. public void DoWork( WorkOrder workOrder ) {
  2.     this.WorkOrder = workOrder ?? throw new System.ArgumentNullException( "workOrder" );
  3.     var steps = ( this.Steps ?? new IStep[ 0 ] ).OfType<IStep>();
  4.     if ( !steps.Any() ) {
  5.         return;
  6.     }
  7.     using ( var tokenSource = new System.Threading.CancellationTokenSource() ) {
  8.         var token = tokenSource.Token;
  9.         var maxP = this.MaxDegreeOfParallelism;
  10.         if ( DefaultMaxDegreeOfParallelism == maxP ) {
  11.             this.DoUnlimitedWork( workOrder, steps, token );
  12.         } else {
  13.             this.DoLimitedWork( workOrder, steps, token, maxP );
  14.         }
  15.     }
  16. }
  17. private void DoUnlimitedWork( WorkOrder workOrder, System.Collections.Generic.IEnumerable<IStep> steps, System.Threading.CancellationToken token ) {
  18.     System.Collections.Generic.ICollection<System.Threading.Tasks.Task> tasks = new System.Collections.Generic.List<System.Threading.Tasks.Task>();
  19.     var factory = new System.Threading.Tasks.TaskFactory(
  20.         token,
  21.         System.Threading.Tasks.TaskCreationOptions.LongRunning,
  22.         System.Threading.Tasks.TaskContinuationOptions.LongRunning,
  23.         System.Threading.Tasks.TaskScheduler.Default
  24.     );
  25.     foreach ( var step in steps ) {
  26.         tasks.Add( factory.StartNew(
  27.             () => step.DoWork( workOrder ),
  28.             token
  29.         ) );
  30.     }
  31.     System.Threading.Tasks.Task.WaitAll( tasks.ToArray(), token );
  32. }
  33. private void DoLimitedWork( WorkOrder workOrder, System.Collections.Generic.IEnumerable<IStep> steps, System.Threading.CancellationToken token, System.Int32 MaxDegreeOfParallelism ) {
  34.     using ( var semaphore = new Semaphore( this.MaxDegreeOfParallelism, this.MaxDegreeOfParallelism ) ) {
  35.         System.Collections.Generic.ICollection<System.Threading.Tasks.Task> tasks = new System.Collections.Generic.List<System.Threading.Tasks.Task>();
  36.         var factory = new System.Threading.Tasks.TaskFactory( token );
  37.         foreach ( var step in steps ) {
  38.             tasks.Add( factory.StartNew(
  39.                 () => {
  40.                     semaphore.Wait();
  41.                     step.DoWork( workOrder );
  42.                     semaphore.Release();
  43.                 },
  44.                 token
  45.             ) );
  46.         }
  47.         System.Threading.Tasks.Task.WaitAll( tasks.ToArray(), token );
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement