C# Class BitSharper.Threading.Execution.ThreadPoolExecutor

An IExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors.NewCachedThreadPool() (unbounded thread pool, with automatic thread reclamation), Executors.NewFixedThreadPool(int) or Executors.NewFixedThreadPool(int, IThreadFactory ) (fixed size thread pool) and Executors.NewSingleThreadExecutor() single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:

Core and maximum pool sizes> A ThreadPoolExecutor will automatically adjustthe pool size (PoolSize) according to the bounds set by Core Pool Size (CorePoolSize) and Maximum Pool Size (MaximumPoolSize)

When a new task is submitted in method AbstractExecutorService.Execute(Action) or AbstractExecutorService.Execute(IRunnable) and fewer than CorePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than CorePoolSize but less than MaximumPoolSize threads running, a new thread will be created only if the queue is full. By setting core pool size and maximum pool size the same, you create a fixed-size thread pool. By setting maximum pool size to an essentially unbounded value such as int.MaxValue, you allow the pool to accommodate an arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using CorePoolSize and MaximumPoolSize. On-demand construction By default, even core threads are initially created and started only when new tasks arrive, but this can be overridden dynamically using method PreStartCoreThread or PreStartAllCoreThreads(). You probably want to prestart threads if you construct the pool with a non-empty queue. Creating new threads New threads are created using a IThreadFactory. If not otherwise specified, a Executors.DefaultThreadFactory is used, that creates threads to all with the same ThreadPriority set to ThreadPriority.Normal priority and non-daemon status. By supplying a different IThreadFactory, you can alter the thread's name, priority, daemon status, etc. If a IThreadFactory fails to create a thread when asked by returning null from IThreadFactory.NewThread(IRunnable), the executor will continue, but might not be able to execute any tasks. Keep-alive times If the pool currently has more than CorePoolSize threads, excess threads will be terminated if they have been idle for more than the KeepAliveTime. This provides a means of reducing resource consumption when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method KeepAliveTime. Using a value of System.Int32.MaxValue effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than CorePoolSize Threads. But method AllowsCoreThreadsToTimeOut can be used to apply this time-out policy to core threads as well, so long as the KeepAliveTime value is non-zero. Queuing Any IBlockingQueue{T} may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing: If fewer than CorePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing. If CorePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread. If a request cannot be queued, a new thread is created unless this would exceed MaximumPoolSize, in which case, the task will be rejected. There are three general strategies for queuing: Direct handoffs. A good default choice for a work queue is a SynchronousQueue{T} that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded MaximumPoolSize to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed. Unbounded queues. Using an unbounded queue (for example a LinkedBlockingQueue{T} without a predefined capacity) will cause new tasks to wait in the queue when all CorePoolSize threads are busy. Thus, no more than CorePoolSize threads will ever be created. (And the value of the MaximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed. Bounded queues. A bounded queue helps prevent resource exhaustion when used with finite MaximumPoolSize, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may be traded off for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput. Rejected tasks New tasks submitted in method AbstractExecutorService.Execute(Action) or AbstractExecutorService.Execute(IRunnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the AbstractExecutorService.Execute(Action) or AbstractExecutorService.Execute(IRunnable) method invokes the IRejectedExecutionHandler.RejectedExecution method of its IRejectedExecutionHandler. Four predefined handler policies are provided: In the default AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection. In CallerRunsPolicy, the thread that invokes AbstractExecutorService.Execute(Action) or AbstractExecutorService.Execute(IRunnable) itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted. In DiscardPolicy, a task that cannot be executed is simply dropped. In DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.) It is possible to define and use other kinds of IRejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies. Hook methods This class provides protected overridable BeforeExecute and AfterExecute methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method Terminated can be overridden to perform any special processing that needs to be done once the Executor has fully terminated.

If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate. Queue maintenance Method Queue allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged. Finalization A pool that is no longer referenced in a program AND has no remaining threads will be Shutdown automatically. If you would like to ensure that unreferenced pools are reclaimed even if users forget to call Shutdown, then you must arrange that unused threads eventually die, by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting AllowsCoreThreadsToTimeOut. Extension example. Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature: internal class PausableThreadPoolExecutor : ThreadPoolExecutor { private boolean _isPaused; private ReentrantLock _pauseLock = new ReentrantLock(); private ICondition _unpaused = pauseLock.NewCondition(); public PausableThreadPoolExecutor(...) : base( ... ) { } protected override void BeforeExecute(Thread t, IRunnable r) { base.BeforeExecute(t, r); _pauseLock.Lock(); try { while (_isPaused) _unpaused.Await(); } catch (ThreadInterruptedException ie) { t.Interrupt(); } finally { _pauseLock.Unlock(); } } public void Pause() { using(_pauseLock.Lock()) { _isPaused = true; } } public void Resume() { using(_pauseLock.Lock()) { _isPaused = false; _unpaused.SignalAll(); } } }

Inheritance: AbstractExecutorService, IRecommendParallelism
Mostra file Open project: TangibleCryptography/BitSharper Class Usage Examples

Private Properties

Property Type Description
AddWorker bool
AdvanceRunState void
ClearInterruptsForTaskRun void
CompareAndDecrementWorkerCount bool
CompareAndIncrementWorkerCount bool
ControlOf int
DecrementWorkerCount void
DrainQueue IList
GetTask IRunnable
InterruptIdleWorkers void
InterruptIdleWorkers void
InterruptWorkers void
IsRunning bool
IsRunningOrShutdown bool
ProcessWorkerExit void
Reject void
RunStateAtLeast bool
RunStateLessThan bool
RunStateOf int
RunWorker void
TryTerminate void
WorkerCountOf int

Public Methods

Method Description
AwaitTermination ( System.TimeSpan duration ) : bool

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Dispose ( ) : void

Shutsdown and disposes of this ThreadPoolExecutor.

PreStartAllCoreThreads ( ) : int

Starts all core threads, causing them to idly wait for work.

This overrides the default policy of starting core threads only when new tasks are executed.

PreStartCoreThread ( ) : bool

Starts a core thread, causing it to idly wait for work. This overrides the default policy of starting core threads only when new tasks are executed. This method will return false if all core threads have already been started.

Purge ( ) : void

Tries to remove from the work queue all IFuture{T} tasks that have been cancelled. This method can be useful as a storage reclamation operation, that has no other impact on functionality. Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively remove them. Invoking this method instead tries to remove them now. However, this method may fail to remove tasks in the presence of interference by other threads.

Remove ( Action task ) : bool

Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.

This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.

Remove ( IRunnable task ) : bool

Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.

This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.

Shutdown ( ) : void

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

ShutdownNow ( ) : IList

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.Interrupt, so any task that fails to respond to interrupts may never terminate.

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue ) : System

Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler.

> It may be more convenient to use one of the Executors factory methods instead of this general purpose constructor.

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue, IRejectedExecutionHandler handler ) : System

Creates a new ThreadPoolExecutor with the given initial parameters and IThreadFactory.

Creates a new ThreadPoolExecutor with the given initial parameters and default RejectedExecutionException.

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory ) : System

Creates a new ThreadPoolExecutor with the given initial parameters and default RejectedExecutionException.

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory, IRejectedExecutionHandler handler ) : System

Creates a new ThreadPoolExecutor with the given initial parameters.

Protected Methods

Method Description
AfterExecute ( IRunnable runnable, Exception exception ) : void

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the exception is the unhandle exception that caused execution to terminate abruptly.

This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.AfterExecute at the beginning of this method.

Note: When actions are enclosed in tasks (such as FutureTask{T}) either explicitly or via methods such as IExecutorService.Submit(System.Action), these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. If you would like to trap both kinds of failures in this method, you can further probe for such cases, as in this sample subclass that prints either the direct cause or the underlying exception if a task has been aborted:

class ExtendedExecutor : ThreadPoolExecutor { // ... protected void AfterExecute(IRunnable r, Exception t) { base.AfterExecute(r, t); if (t == null && r is IFuture) { try { Object result = ((IFuture) r).GetResult(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.InnerException; } catch (InterruptedException ie) { Thread.CurrentThread.Interrupt(); // ignore/reset } } if (t != null) Console.WriteLine(t); } }
BeforeExecute ( Thread thread, IRunnable runnable ) : void

Method invoked prior to executing the given IRunnable in the given thread.

This method is invoked by thread that will execute runnable, and may be used to re-initialize ThreadLocals, or to perform logging. This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.BeforeExecute at the end of this method.

Dispose ( bool disposing ) : void

Helper method to dispose of this ThreadPoolExecutor

DoExecute ( IRunnable command ) : void

Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread.

If the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current IRejectedExecutionHandler for this ThreadPoolExecutor.

OnShutdown ( ) : void

Performs any further cleanup following run state transition on invocation of shutdown. A no-op here, but used by ScheduledThreadPoolExecutor to cancel delayed tasks.

Terminated ( ) : void

Method invoked when the IExecutor has terminated. Default implementation does nothing.

Note: To properly nest multiple overridings, subclasses should generally invoke base.terminated within this method.

Private Methods

Method Description
AddWorker ( IRunnable firstTask, bool core ) : bool

Checks if a new worker can be added with respect to current pool state and the given bound (either core or maximum). If so, the worker count is adjusted accordingly, and, if possible, a new worker is created and started running firstTask as its first task. This method returns false if the pool is stopped or eligible to shut down. It also returns false if the thread factory fails to create a thread when asked, which requires a backout of workerCount, and a recheck for termination, in case the existence of this worker was holding up termination.

AdvanceRunState ( int targetState ) : void

Transitions control state to given target or leaves if alone if already at least the given target.

ClearInterruptsForTaskRun ( ) : void

Ensures that unless the pool is stopping, the current thread does not have its interrupt set. This requires a double-check of state in case the interrupt was cleared concurrently with a shutdownNow -- if so, the interrupt is re-enabled.

CompareAndDecrementWorkerCount ( int expect ) : bool

Attempt to CAS-decrement the workerCount field of control state.

CompareAndIncrementWorkerCount ( int expect ) : bool

Attempt to CAS-increment the workerCount field of control state.

ControlOf ( int rs, int wc ) : int
DecrementWorkerCount ( ) : void

Decrements the workerCount field of ctl. This is called only on abrupt termination of a thread (see ProcessWorkerExit). Other decrements are performed within GetTask.

DrainQueue ( ) : IList

Drains the task queue into a new list, normally using drainTo. But if the queue is a DelayQueue or any other kind of queue for which poll or drainTo may fail to remove some elements, it deletes them one by one.

GetTask ( ) : IRunnable

Performs blocking or timed wait for a task, depending on current configuration settings, or returns null if this worker must exit because of any of: 1. There are more than maximumPoolSize workers (due to a call to setMaximumPoolSize). 2. The pool is stopped. 3. The pool is shutdown and the queue is empty. 4. This worker timed out waiting for a task, and timed-out workers are subject to termination (that is, allowCoreThreadTimeOut || workerCount > corePoolSize) both before and after the timed wait.

InterruptIdleWorkers ( ) : void

Interrupts all threads that might be waiting for tasks.

InterruptIdleWorkers ( bool onlyOne ) : void

Interrupts threads that might be waiting for tasks (as indicated by not being locked) so they can check for termination or configuration changes. Ignores SecurityExceptions (in which case some threads may remain uninterrupted). @param onlyOne If true, interrupt at most one worker. This is called only from TryTerminate when termination is otherwise enabled but there are still other workers. In this case, at most one waiting worker is interrupted to propagate shutdown signals in case all threads are currently waiting. Interrupting any arbitrary thread ensures that newly arriving workers since shutdown began will also eventually exit. To guarantee eventual termination, it suffices to always interrupt only one idle worker, but shutdown() interrupts all idle workers so that redundant workers exit promptly, not waiting for a straggler task to finish.

InterruptWorkers ( ) : void

Interrupts all threads, even if active. Ignores SecurityExceptions (in which case some threads may remain uninterrupted).

IsRunning ( int c ) : bool
IsRunningOrShutdown ( bool shutdownOK ) : bool

State check needed by ScheduledThreadPoolExecutor to enable running tasks during shutdown.

ProcessWorkerExit ( Worker w, bool completedAbruptly ) : void

Performs cleanup and bookkeeping for a dying worker. Called only from worker threads. Unless completedAbruptly is set, assumes that workerCount has already been adjusted to account for exit. This method removes thread from worker set, and possibly terminates the pool or replaces the worker if either it exited due to user task exception or if fewer than corePoolSize workers are running or queue is non-empty but there are no workers. the worker if the worker died to the user exception

Reject ( IRunnable command ) : void

Invokes the rejected execution handler for the given command.

RunStateAtLeast ( int c, int s ) : bool
RunStateLessThan ( int c, int s ) : bool

Bit field accessors that don't require unpacking _controlState. These depend on the bit layout and on workerCount being never negative.

RunStateOf ( int c ) : int
RunWorker ( Worker worker ) : void

Main worker run loop. Repeatedly gets tasks from queue and executes them, while coping with a number of issues: 1. We may start out with an initial task, in which case we don't need to get the first one. Otherwise, as long as pool is running, we get tasks from GetTask. If it returns null then the worker exits due to changed pool state or configuration parameters. Other exits result from exception throws in external code, in which case completedAbruptly holds, which usually leads ProcessWorkerExit to replace this thread. 2. Before running any task, the lock is acquired to prevent other pool interrupts while the task is executing, and ClearInterruptsForTaskRun called to ensure that unless pool is stopping, this thread does not have its interrupt set. 3. Each task run is preceded by a call to BeforeExecute, which might throw an exception, in which case we cause thread to die (breaking loop with completedAbruptly true) without processing the task. 4. Assuming BeforeExecute completes normally, we run the task, gathering any of its thrown exceptions to send to AfterExecute. We separately handle RuntimeException, Error (both of which the specs guarantee that we trap) and arbitrary Throwables. Because we cannot rethrow Throwables within Runnable.run, we wrap them within Errors on the way out (to the thread's UncaughtExceptionHandler). Any thrown exception also conservatively causes thread to die. 5. After task.run completes, we call AfterExecute, which may also throw an exception, which will also cause thread to die. According to JLS Sec 14.20, this exception is the one that will be in effect even if task.run throws. The net effect of the exception mechanics is that AfterExecute and the thread's UncaughtExceptionHandler have as accurate information as we can provide about any problems encountered by user code. the worker to run

TryTerminate ( ) : void

Transitions to TERMINATED state if either (SHUTDOWN and pool and queue empty) or (STOP and pool empty). If otherwise eligible to terminate but workerCount is nonzero, interrupts an idle worker to ensure that shutdown signals propagate. This method must be called following any action that might make termination possible -- reducing worker count or removing tasks from the queue during shutdown. The method is non-private to allow access from ScheduledThreadPoolExecutor.

WorkerCountOf ( int c ) : int

Method Details

AfterExecute() protected method

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the exception is the unhandle exception that caused execution to terminate abruptly.

This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.AfterExecute at the beginning of this method.

Note: When actions are enclosed in tasks (such as FutureTask{T}) either explicitly or via methods such as IExecutorService.Submit(System.Action), these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. If you would like to trap both kinds of failures in this method, you can further probe for such cases, as in this sample subclass that prints either the direct cause or the underlying exception if a task has been aborted:

class ExtendedExecutor : ThreadPoolExecutor { // ... protected void AfterExecute(IRunnable r, Exception t) { base.AfterExecute(r, t); if (t == null && r is IFuture) { try { Object result = ((IFuture) r).GetResult(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.InnerException; } catch (InterruptedException ie) { Thread.CurrentThread.Interrupt(); // ignore/reset } } if (t != null) Console.WriteLine(t); } }
protected AfterExecute ( IRunnable runnable, Exception exception ) : void
runnable IRunnable The runnable that has completed.
exception System.Exception /// The exception that caused termination, or null if /// execution completed normally. ///
return void

AwaitTermination() public method

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
public AwaitTermination ( System.TimeSpan duration ) : bool
duration System.TimeSpan the time span to wait. ///
return bool

BeforeExecute() protected method

Method invoked prior to executing the given IRunnable in the given thread.
This method is invoked by thread that will execute runnable, and may be used to re-initialize ThreadLocals, or to perform logging. This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.BeforeExecute at the end of this method.
protected BeforeExecute ( Thread thread, IRunnable runnable ) : void
thread Thread the thread that will run .
runnable IRunnable the task that will be executed.
return void

Dispose() public method

Shutsdown and disposes of this ThreadPoolExecutor.
public Dispose ( ) : void
return void

Dispose() protected method

Helper method to dispose of this ThreadPoolExecutor
protected Dispose ( bool disposing ) : void
disposing bool true if being called from , /// false if being called from finalizer.
return void

DoExecute() protected method

Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread.
If the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current IRejectedExecutionHandler for this ThreadPoolExecutor.
/// if the task cannot be accepted. /// /// if is null ///
protected DoExecute ( IRunnable command ) : void
command IRunnable the task to execute
return void

OnShutdown() protected method

Performs any further cleanup following run state transition on invocation of shutdown. A no-op here, but used by ScheduledThreadPoolExecutor to cancel delayed tasks.
protected OnShutdown ( ) : void
return void

PreStartAllCoreThreads() public method

Starts all core threads, causing them to idly wait for work.
This overrides the default policy of starting core threads only when new tasks are executed.
public PreStartAllCoreThreads ( ) : int
return int

PreStartCoreThread() public method

Starts a core thread, causing it to idly wait for work. This overrides the default policy of starting core threads only when new tasks are executed. This method will return false if all core threads have already been started.
public PreStartCoreThread ( ) : bool
return bool

Purge() public method

Tries to remove from the work queue all IFuture{T} tasks that have been cancelled. This method can be useful as a storage reclamation operation, that has no other impact on functionality. Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively remove them. Invoking this method instead tries to remove them now. However, this method may fail to remove tasks in the presence of interference by other threads.
public Purge ( ) : void
return void

Remove() public method

Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.
This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.
public Remove ( Action task ) : bool
task Action The task to remove.
return bool

Remove() public method

Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.
This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.
public Remove ( IRunnable task ) : bool
task IRunnable The task to remove.
return bool

Shutdown() public method

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
public Shutdown ( ) : void
return void

ShutdownNow() public method

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.Interrupt, so any task that fails to respond to interrupts may never terminate.

public ShutdownNow ( ) : IList
return IList

Terminated() protected method

Method invoked when the IExecutor has terminated. Default implementation does nothing.

Note: To properly nest multiple overridings, subclasses should generally invoke base.terminated within this method.

protected Terminated ( ) : void
return void

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler.
> It may be more convenient to use one of the Executors factory methods instead of this general purpose constructor.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
return System

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters and IThreadFactory. Creates a new ThreadPoolExecutor with the given initial parameters and default RejectedExecutionException.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if or is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue, IRejectedExecutionHandler handler ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
handler IRejectedExecutionHandler /// The to use when execution is blocked /// because the thread bounds and queue capacities are reached. ///
return System

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters and default RejectedExecutionException.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if or is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
threadFactory IThreadFactory /// to use for new thread creation. ///
return System

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if , , or is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory, IRejectedExecutionHandler handler ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
threadFactory IThreadFactory /// to use for new thread creation. ///
handler IRejectedExecutionHandler /// The to use when execution is blocked /// because the thread bounds and queue capacities are reached. ///
return System