Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2014
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.37 KB | None | 0 0
  1. internal class ThrottlePool
  2. {
  3.     #region Worker
  4.  
  5.     internal class Worker
  6.     {
  7.         public object   Request;
  8.  
  9.         public Delegate Callback;
  10.  
  11.         public Delegate Action;
  12.     }
  13.  
  14.     #endregion
  15.  
  16.     private int concurrency;
  17.  
  18.     private int running;
  19.  
  20.     private System.Collections.Generic.Queue<Worker> workers;
  21.  
  22.     public ThrottlePool(int concurrency)
  23.     {
  24.         this.concurrency = concurrency;
  25.  
  26.         this.running     = 0;
  27.  
  28.         this.workers     = new Queue<Worker>();
  29.     }
  30.  
  31.     public void Run<TRequest, TResponse>(Reactor.Action<TRequest, Reactor.Action<System.Exception, TResponse>> action, TRequest request, Reactor.Action<Exception, TResponse> callback)
  32.     {
  33.         this.workers.Enqueue(new Worker {
  34.  
  35.             Request  = request,
  36.  
  37.             Callback = callback,
  38.  
  39.             Action   = action,
  40.         });
  41.  
  42.         this.Process();
  43.     }
  44.  
  45.     private void Process()
  46.     {
  47.         if (this.workers.Count > 0) {
  48.  
  49.             if (this.running < this.concurrency) {
  50.  
  51.                 var worker = this.workers.Dequeue();
  52.  
  53.                 this.running++;
  54.  
  55.                 var paramters = worker.Callback.Method.GetParameters();
  56.  
  57.                 var callback = Reactor.DynamicAction.Create(new System.Type[] { paramters[0].ParameterType,
  58.                    
  59.                                                                             paramters[1].ParameterType }, (results) => {
  60.                     this.running--;
  61.                    
  62.                     worker.Callback.DynamicInvoke(results);
  63.  
  64.                     this.Process();
  65.                 });
  66.  
  67.                 worker.Action.DynamicInvoke(new object[] { worker.Request, callback });
  68.             }
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement