##// END OF EJS Templates
added ICancellable.Cancel(Exception) to allow specify the reason of cancellation
added ICancellable.Cancel(Exception) to allow specify the reason of cancellation

File last commit:

r129:471f596b2603 v2
r138:f75cfa58e3d4 v2
Show More
WorkerPool.cs
82 lines | 2.2 KiB | text/x-csharp | CSharpLexer
using System;
using System.Threading;
using System.Diagnostics;
using Implab.Diagnostics;
namespace Implab.Parallels {
public class WorkerPool : DispatchPool<Action> {
AsyncQueue<Action> m_queue = new AsyncQueue<Action>();
int m_queueLength;
readonly int m_threshold = 1;
public WorkerPool(int minThreads, int maxThreads, int threshold)
: base(minThreads, maxThreads) {
m_threshold = threshold;
InitPool();
}
public WorkerPool(int minThreads, int maxThreads) :
base(minThreads, maxThreads) {
InitPool();
}
public WorkerPool(int threads)
: base(threads) {
InitPool();
}
public WorkerPool() {
InitPool();
}
public Promise<T> Invoke<T>(Func<T> task) {
if (task == null)
throw new ArgumentNullException("task");
if (IsDisposed)
throw new ObjectDisposedException(ToString());
var promise = new Promise<T>();
var lop = TraceContext.Instance.CurrentOperation;
EnqueueTask(delegate {
TraceContext.Instance.EnterLogicalOperation(lop, false);
try {
promise.Resolve(task());
} catch (Exception e) {
promise.Reject(e);
} finally {
TraceContext.Instance.Leave();
}
});
return promise;
}
protected void EnqueueTask(Action unit) {
Debug.Assert(unit != null);
var len = Interlocked.Increment(ref m_queueLength);
m_queue.Enqueue(unit);
if (len > m_threshold * PoolSize) {
StartWorker();
}
SignalThread();
}
protected override bool TryDequeue(out Action unit) {
if (m_queue.TryDequeue(out unit)) {
Interlocked.Decrement(ref m_queueLength);
return true;
}
return false;
}
protected override void InvokeUnit(Action unit) {
unit();
}
}
}