private void OnTimedEvent(Timer timer, IThreadRunnable task)
 {
     lock (this)
     {
         this._timers.Remove(timer);
     }
     task.Run();
 }
        /// <summary>
        /// Creates a new <seealso cref="Thread"/>
        /// </summary>
        /// <seealso cref= java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) </seealso>
        public override Thread NewThread(IThreadRunnable r)
        {
            Thread t = new Thread(r.Run)
            {
                Name = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", this.ThreadNamePrefix, Interlocked.Increment(ref ThreadNumber)),
                IsBackground = false,
                Priority = ThreadPriority.Normal
            };

            return t;
        }
 public void Schedule(IThreadRunnable task, long delay)
 {
     Timer timer = new Timer();
     TimerTask task2 = new TimerTask(this, timer, task);
     timer.Elapsed += new ElapsedEventHandler(task2.OnTimedEvent);
     timer.AutoReset = false;
     timer.Interval = (delay < 1L) ? ((double) 1L) : ((double) delay);
     lock (this)
     {
         this._timers.Add(timer);
     }
     timer.Start();
 }
示例#4
0
 public void Schedule(IThreadRunnable task, long delay)
 {
     TimerCallback cb = new TimerCallback(this.OnTimedEvent);
     TimerContext context = new TimerContext {
         task = task
     };
     Timer timer = new Timer(cb, context, -1, 0);
     context.timer = timer;
     lock (this)
     {
         this._timers.Add(timer);
     }
     timer.Change((delay < 1L) ? 1L : delay, 0L);
 }
        /// <summary>
        /// Execute the given <see cref="T:Quartz.IThreadRunnable"/> in the next
        /// available <see cref="T:System.Threading.Thread"/>.
        /// </summary>
        /// <param name="runnable"></param>
        /// <returns></returns>
        /// <remarks>
        /// The implementation of this interface should not throw exceptions unless
        /// there is a serious problem (i.e. a serious misconfiguration). If there
        /// are no available threads, rather it should either queue the Runnable, or
        /// block until a thread is available, depending on the desired strategy.
        /// </remarks>
		public virtual bool RunInThread(IThreadRunnable runnable)
		{
			if (runnable == null)
			{
				return false;
			}
			try
			{
				taskExecutor.Execute(runnable.Run);
				return true;
			}
			catch (TaskRejectedException ex)
			{
				logger.Error("Task has been rejected by TaskExecutor", ex);
				return false;
			}
		}
 /// <summary> Runs the run method of the specified target in an idle thread of this
 /// pool. When the target's run method completes, the thread waiting on the
 /// lock object is notified, if any. If there is currently no idle thread
 /// the method will block until a thread of the pool becomes idle or the
 /// calling thread is interrupted.
 ///
 /// <P>This method is the same as <tt>runTarget(t,l,true,false)</tt>.
 ///
 /// </summary>
 /// <param name="t">The target. The 'run()' method of this object will be run in
 /// an idle thread of the pool.
 ///
 /// </param>
 /// <param name="l">The lock object. A thread waiting on the lock of the 'l'
 /// object will be notified, through the 'notify()' call, when the target's
 /// run method completes. If null no thread is notified.
 ///
 /// </param>
 /// <returns> True if the target was submitted to some thread. False if no
 /// idle thread could be found and the target was not submitted for
 /// execution.
 ///
 ///
 /// </returns>
 public virtual bool runTarget(IThreadRunnable t, System.Object l)
 {
     return(runTarget(t, l, false, false));
 }
 /// <summary> The method that is run by the thread. This method first joins the
 /// idle state in the pool and then enters an infinite loop. In this
 /// loop it waits until a target to run exists and runs it. Once the
 /// target's run() method is done it re-joins the idle state and
 /// notifies the waiting lock object, if one exists.
 ///
 /// <P>An interrupt on this thread has no effect other than forcing a
 /// check on the target. Normally the target is checked every time the
 /// thread is woken up by notify, no interrupts should be done.
 ///
 /// <P>Any exception thrown by the target's 'run()' method is catched
 /// and this thread is not affected, except for 'ThreadDeath'. If a
 /// 'ThreadDeath' exception is catched a warning message is printed by
 /// the 'FacilityManager' and the exception is propagated up. For
 /// exceptions which are subclasses of 'Error' or 'RuntimeException'
 /// the corresponding error condition is set and this thread is not
 /// affected. For any other exceptions a new 'RuntimeException' is
 /// created and the error condition is set, this thread is not affected.
 ///
 /// </summary>
 override public void  Run()
 {
     // Join the idle threads list
     Enclosing_Instance.putInIdleList(this);
     // Permanently lock the object while running so that target can
     // not be changed until we are waiting again. While waiting for a
     // target the lock is released.
     lock (this)
     {
         while (true)
         {
             // Wait until we get a target
             while (target == null)
             {
                 try
                 {
                     System.Threading.Monitor.Wait(this);
                 }
                 catch (System.Threading.ThreadInterruptedException)
                 {
                 }
             }
             // Run the target and catch all possible errors
             try
             {
                 target.Run();
             }
             //UPGRADE_NOTE: Exception 'java.lang.ThreadDeath' was converted to 'System.ApplicationException' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
             catch (System.Threading.ThreadAbortException td)
             {
                 // We have been instructed to abruptly terminate
                 // the thread, which should never be done. This can
                 // cause another thread, or the system, to lock.
                 FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Thread.stop() called on a ThreadPool " + "thread or ThreadDeath thrown. This is " + "deprecated. Lock-up might occur.");
                 throw td;
             }
             catch (System.ApplicationException e)
             {
                 Enclosing_Instance.targetE = e;
             }
             catch (System.SystemException re)
             {
                 Enclosing_Instance.targetRE = re;
             }
             //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
             catch (System.Exception)
             {
                 // A totally unexpected error has occurred
                 // (Thread.stop(Throwable) has been used, which should
                 // never be.
                 Enclosing_Instance.targetRE = new System.SystemException("Unchecked exception " + "thrown by target's " + "run() method in pool " + Enclosing_Instance.poolName + ".");
             }
             // Join idle threads
             Enclosing_Instance.putInIdleList(this);
             // Release the target and notify lock (i.e. wakeup)
             target = null;
             if (lock_Renamed != null)
             {
                 lock (lock_Renamed)
                 {
                     if (doNotifyAll)
                     {
                         System.Threading.Monitor.PulseAll(lock_Renamed);
                     }
                     else
                     {
                         System.Threading.Monitor.Pulse(lock_Renamed);
                     }
                 }
             }
         }
     }
 }
示例#8
0
 public abstract Thread NewThread(IThreadRunnable r);
示例#9
0
            public void Run(IThreadRunnable newRunnable)
            {
                lock (this)
                {
                    if (runnable != null)
                    {
                        throw new ArgumentException("Already running a Runnable!");
                    }

                    runnable = newRunnable;
                    Monitor.PulseAll(this);
                }
            }
示例#10
0
            /// <summary>
            /// Loop, executing targets as they are received.
            /// </summary>
            public override void Run()
            {
                bool ran = false;
                bool shouldRun;

                lock (this)
                {
                    shouldRun = run;
                }

                while (shouldRun)
                {
                    try
                    {
                        lock (this)
                        {
                            while (runnable == null && run)
                            {
                                Monitor.Wait(this, 500);
                            }
                            if (runnable != null)
                            {
                                ran = true;
                                runnable.Run();
                            }
                        }
                    }
                    catch (Exception exceptionInRunnable)
                    {
                        log.Error("Error while executing the Runnable: ", exceptionInRunnable);
                    }
                    finally
                    {
                        lock (this)
                        {
                            runnable = null;
                        }
                        // repair the thread in case the runnable mucked it up...
                        if (Priority != tp.ThreadPriority)
                        {
                            Priority = tp.ThreadPriority;
                        }

                        if (runOnce)
                        {
                            lock (this)
                            {
                                run = false;
                            }
                            tp.ClearFromBusyWorkersList(this);
                        }
                        else if (ran)
                        {
                            ran = false;
                            tp.MakeAvailable(this);
                        }
                    }

                    // read value of run within synchronized block to be
                    // sure of its value
                    lock (this)
                    {
                        shouldRun = run;
                    }
                }

                log.Debug("WorkerThread is shut down");
            }
示例#11
0
            /// <summary>
            /// Loop, executing targets as they are received.
            /// </summary>
            public override void Run()
            {
                bool ran = false;

                while (run)
                {
                    try
                    {
                        lock (lockObject)
                        {
                            while (runnable == null && run)
                            {
                                Monitor.Wait(lockObject, 500);
                            }
                            if (runnable != null)
                            {
                                ran = true;
                                runnable.Run();
                            }

                        }
                    }
                    catch (Exception exceptionInRunnable)
                    {
                        log.Error("Error while executing the Runnable: ", exceptionInRunnable);
                    }
                    finally
                    {
                        lock (lockObject)
                        {
                            runnable = null;
                        }
                        // repair the thread in case the runnable mucked it up...
                        Priority = tp.ThreadPriority;

                        if (runOnce)
                        {
                            run = false;
                            tp.ClearFromBusyWorkersList(this);
                        }
                        else if (ran)
                        {
                            ran = false;
                            tp.MakeAvailable(this);
                        }
                    }
                }

                log.Debug("WorkerThread is shut down");
            }
示例#12
0
		/// <summary> Runs the run method of the specified target in an idle thread of this
		/// pool. When the target's run method completes, the thread waiting on the
		/// lock object is notified, if any. If there is currently no idle thread
		/// and the asynchronous mode is not used the method will block until a
		/// thread of the pool becomes idle or the calling thread is
		/// interrupted. If the asynchronous mode is used then the method will not
		/// block and will return false.
		/// 
		/// </summary>
		/// <param name="t">The target. The 'run()' method of this object will be run in
		/// an idle thread of the pool.
		/// 
		/// </param>
		/// <param name="l">The lock object. A thread waiting on the lock of the 'l'
		/// object will be notified, through the 'notify()' call, when the target's 
		/// run method completes. If null no thread is notified.
		/// 
		/// </param>
		/// <param name="async">If true the asynchronous mode will be used.
		/// 
		/// </param>
		/// <param name="notifyAll">If true, threads waiting on the lock of the 'l' object
		/// will be notified trough the 'notifyAll()' instead of the normal
		/// 'notify()' call. This is not normally needed.
		/// 
		/// </param>
		/// <returns> True if the target was submitted to some thread. False if no
		/// idle thread could be found and the target was not submitted for
		/// execution.
		/// 
		/// 
		/// </returns>
		public virtual bool runTarget(IThreadRunnable t, System.Object l, bool async, bool notifyAll)
		{
			ThreadPoolThread runner; // The thread to run the target
			
			// Get a thread to run
			runner = getIdle(async);
			// If no runner return failure
			if (runner == null)
				return false;
			// Set the runner
			runner.setTarget(t, l, notifyAll);
			return true;
		}
示例#13
0
		/// <summary> Runs the run method of the specified target in an idle thread of this
		/// pool. When the target's run method completes, the thread waiting on the
		/// lock object is notified, if any. If there is currently no idle thread
		/// and the asynchronous mode is not used the method will block until a
		/// thread of the pool becomes idle or the calling thread is
		/// interrupted. If the asynchronous mode is used then the method will not
		/// block and will return false.
		/// 
		/// <P>This method is the same as <tt>runTarget(t,l,async,false)</tt>.
		/// 
		/// </summary>
		/// <param name="t">The target. The 'run()' method of this object will be run in
		/// an idle thread of the pool.
		/// 
		/// </param>
		/// <param name="l">The lock object. A thread waiting on the lock of the 'l'
		/// object will be notified, through the 'notify()' call, when the target's 
		/// run method completes. If null no thread is notified.
		/// 
		/// </param>
		/// <param name="async">If true the asynchronous mode will be used.
		/// 
		/// </param>
		/// <returns> True if the target was submitted to some thread. False if no
		/// idle thread could be found and the target was not submitted for
		/// execution.
		/// 
		/// 
		/// </returns>
		public virtual bool runTarget(IThreadRunnable t, System.Object l, bool async)
		{
			return runTarget(t, l, async, false);
		}
示例#14
0
		/// <summary> Runs the run method of the specified target in an idle thread of this
		/// pool. When the target's run method completes, the thread waiting on the
		/// lock object is notified, if any. If there is currently no idle thread
		/// the method will block until a thread of the pool becomes idle or the
		/// calling thread is interrupted.
		/// 
		/// <P>This method is the same as <tt>runTarget(t,l,true,false)</tt>.
		/// 
		/// </summary>
		/// <param name="t">The target. The 'run()' method of this object will be run in
		/// an idle thread of the pool.
		/// 
		/// </param>
		/// <param name="l">The lock object. A thread waiting on the lock of the 'l'
		/// object will be notified, through the 'notify()' call, when the target's 
		/// run method completes. If null no thread is notified.
		/// 
		/// </param>
		/// <returns> True if the target was submitted to some thread. False if no
		/// idle thread could be found and the target was not submitted for
		/// execution.
		/// 
		/// 
		/// </returns>
		public virtual bool runTarget(IThreadRunnable t, System.Object l)
		{
			return runTarget(t, l, false, false);
		}
示例#15
0
			/// <summary> Assigns a target to this thread, with an optional notify lock and a
			/// notify mode. The another target is currently running the method
			/// will block until it terminates. After setting the new target the
			/// runner thread will be wakenup and execytion will start.
			/// 
			/// </summary>
			/// <param name="target">The runnable object containing the 'run()' method to
			/// run.
			/// 
			/// </param>
			/// <param name="lock">An object on which notify will be called once the
			/// target's run method has finished. A thread to be notified should be 
			/// waiting on that object. If null no thread is notified.
			/// 
			/// </param>
			/// <param name="notifyAll">If true 'notifyAll()', instead of 'notify()', will
			/// be called on tghe lock.
			/// 
			/// </param>
			//UPGRADE_NOTE: Synchronized keyword was removed from method 'setTarget'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'"
			internal virtual void  setTarget(IThreadRunnable target, System.Object lock_Renamed, bool notifyAll)
			{
				lock (this)
				{
					// Set the target
					this.target = target;
					this.lock_Renamed = lock_Renamed;
					doNotifyAll = notifyAll;
					// Wakeup the thread
					System.Threading.Monitor.Pulse(this);
				}
			}
示例#16
0
			/// <summary> The method that is run by the thread. This method first joins the
			/// idle state in the pool and then enters an infinite loop. In this
			/// loop it waits until a target to run exists and runs it. Once the
			/// target's run() method is done it re-joins the idle state and
			/// notifies the waiting lock object, if one exists.
			/// 
			/// <P>An interrupt on this thread has no effect other than forcing a
			/// check on the target. Normally the target is checked every time the
			/// thread is woken up by notify, no interrupts should be done.
			/// 
			/// <P>Any exception thrown by the target's 'run()' method is catched
			/// and this thread is not affected, except for 'ThreadDeath'. If a
			/// 'ThreadDeath' exception is catched a warning message is printed by
			/// the 'FacilityManager' and the exception is propagated up. For
			/// exceptions which are subclasses of 'Error' or 'RuntimeException'
			/// the corresponding error condition is set and this thread is not
			/// affected. For any other exceptions a new 'RuntimeException' is
			/// created and the error condition is set, this thread is not affected.
			/// 
			/// </summary>
			override public void  Run()
			{
				// Join the idle threads list
				Enclosing_Instance.putInIdleList(this);
				// Permanently lock the object while running so that target can
				// not be changed until we are waiting again. While waiting for a
				// target the lock is released.
				lock (this)
				{
					while (true)
					{
						// Wait until we get a target
						while (target == null)
						{
							try
							{
								System.Threading.Monitor.Wait(this);
							}
							catch (System.Threading.ThreadInterruptedException)
							{
							}
						}
						// Run the target and catch all possible errors
						try
						{
							target.Run();
						}
						//UPGRADE_NOTE: Exception 'java.lang.ThreadDeath' was converted to 'System.ApplicationException' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
						catch (System.Threading.ThreadAbortException td)
						{
							// We have been instructed to abruptly terminate
							// the thread, which should never be done. This can
							// cause another thread, or the system, to lock.
							FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Thread.stop() called on a ThreadPool " + "thread or ThreadDeath thrown. This is " + "deprecated. Lock-up might occur.");
							throw td;
						}
						catch (System.ApplicationException e)
						{
							Enclosing_Instance.targetE = e;
						}
						catch (System.SystemException re)
						{
							Enclosing_Instance.targetRE = re;
						}
						//UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
						catch (System.Exception)
						{
							// A totally unexpected error has occurred
							// (Thread.stop(Throwable) has been used, which should 
							// never be.
							Enclosing_Instance.targetRE = new System.SystemException("Unchecked exception " + "thrown by target's " + "run() method in pool " + Enclosing_Instance.poolName + ".");
						}
						// Join idle threads
						Enclosing_Instance.putInIdleList(this);
						// Release the target and notify lock (i.e. wakeup)
						target = null;
						if (lock_Renamed != null)
						{
							lock (lock_Renamed)
							{
								if (doNotifyAll)
								{
									System.Threading.Monitor.PulseAll(lock_Renamed);
								}
								else
								{
									System.Threading.Monitor.Pulse(lock_Renamed);
								}
							}
						}
					}
				}
			}
示例#17
0
        /// <summary>
        /// Run the given <see cref="IThreadRunnable" /> object in the next available
        /// <see cref="Thread" />. If while waiting the thread pool is asked to
        /// shut down, the Runnable is executed immediately within a new additional
        /// thread.
        /// </summary>
        /// <param name="runnable">The <see cref="IThreadRunnable" /> to be added.</param>
        public virtual bool RunInThread(IThreadRunnable runnable)
        {
            if (runnable == null)
            {
                return false;
            }

            lock (nextRunnableLock)
            {
                handoffPending = true;

                // Wait until a worker thread is available
                while ((availWorkers.Count < 1) && !isShutdown)
                {
                    try
                    {
                        Monitor.Wait(nextRunnableLock, 500);
                    }
                    catch (ThreadInterruptedException)
                    {
                    }
                }

                if (!isShutdown)
                {
                    WorkerThread wt = (WorkerThread)availWorkers[0];
                    availWorkers.RemoveAt(0);
                    busyWorkers.Add(wt);
                    wt.Run(runnable);
                }
                else
                {
                    // If the thread pool is going down, execute the Runnable
                    // within a new additional worker thread (no thread from the pool).
                    WorkerThread wt =
                        new WorkerThread(this, "WorkerThread-LastJob", prio, MakeThreadsDaemons, runnable);
                    busyWorkers.Add(wt);
                    workers.Add(wt);
                    wt.Start();
                }
                Monitor.PulseAll(nextRunnableLock);
                handoffPending = false;
            }

            return true;
        }
示例#18
0
 /// <summary>
 /// Execute the given <see cref="IThreadRunnable"/> in the next
 /// available <see cref="Thread"/>.
 /// </summary>
 /// <param name="runnable"></param>
 /// <returns></returns>
 /// <remarks>
 /// The implementation of this interface should not throw exceptions unless
 /// there is a serious problem (i.e. a serious misconfiguration). If there
 /// are no available threads, rather it should either queue the Runnable, or
 /// block until a thread is available, depending on the desired strategy.
 /// </remarks>
 public virtual bool RunInThread(IThreadRunnable runnable)
 {
     throw new NotSupportedException("This ThreadPool should not be used on Scheduler instances that are start()ed.");
 }
 public TimerTask(TimerSupport parent, Timer timer, IThreadRunnable task)
 {
     this.parent = parent;
     this.timer = timer;
     this.task = task;
 }
示例#20
0
 bool IThreadPool.RunInThread(IThreadRunnable runnable)
 {
     throw new NotImplementedException();
 }
示例#21
0
 /// <summary>
 /// Execute the given <see cref="IThreadRunnable"/> in the next
 /// available <see cref="Thread"/>.
 /// </summary>
 /// <param name="runnable"></param>
 /// <returns></returns>
 /// <remarks>
 /// The implementation of this interface should not throw exceptions unless
 /// there is a serious problem (i.e. a serious misconfiguration). If there
 /// are no available threads, rather it should either queue the Runnable, or
 /// block until a thread is available, depending on the desired strategy.
 /// </remarks>
 public virtual bool RunInThread(IThreadRunnable runnable)
 {
     throw new NotSupportedException("This ThreadPool should not be used on Scheduler instances that are start()ed.");
 }
示例#22
0
 /// <summary>
 /// Create a worker thread, start it, Execute the runnable and terminate
 /// the thread (one time execution).
 /// </summary>
 internal WorkerThread(SimpleThreadPool tp, string name,
                       ThreadPriority prio, bool isDaemon, IThreadRunnable runnable)
     : base(name)
 {
     this.tp = tp;
     this.runnable = runnable;
     if (runnable != null)
     {
         runOnce = true;
     }
     Priority = prio;
     IsBackground = isDaemon;
 }
示例#23
0
 bool IThreadPool.RunInThread(IThreadRunnable runnable)
 {
     throw new NotImplementedException();
 }
示例#24
0
            /// <summary>
            /// Loop, executing targets as they are received.
            /// </summary>
            public override void Run()
            {
                bool ran = false;
                bool shouldRun;
                lock (this) 
                {
            	    shouldRun = run;
                }
            
                while (shouldRun) 
                {
                    try
                    {
                        lock (this)
                        {
                            while (runnable == null && run)
                            {
                                Monitor.Wait(this, 500);
                            }
                        }

                        if (runnable != null)
                        {
                            ran = true;
                            runnable.Run();
                        }
                    }
                    catch (Exception exceptionInRunnable)
                    {
                        Log.Error("Error while executing the Runnable: ", exceptionInRunnable);
                    }
                    finally
                    {
                        lock (this)
                        {
                            runnable = null;
                        }
                        // repair the thread in case the runnable mucked it up...
                        if (Priority != tp.ThreadPriority)
                        {
                            Priority = tp.ThreadPriority;
                        }

                        if (runOnce)
                        {
                            lock (this)
                            {
                                run = false;
                            }
                            tp.ClearFromBusyWorkersList(this);
                        }
                        else if (ran)
                        {
                            ran = false;
                            tp.MakeAvailable(this);
                        }

                    }
                    
                    // read value of run within synchronized block to be 
                    // sure of its value
                    lock (this) 
                    {
                	    shouldRun = run;
                    }
                }
                
                Log.Debug("WorkerThread is shut down");
            }
示例#25
0
 protected virtual WorkerThread CreateWorkerThread(string name, IThreadRunnable runnable)
 {
     return(new WorkerThread(this, name, ThreadPriority, MakeThreadsDaemons, runnable));
 }