Esempio n. 2
0
        public virtual void Queue(WaitCallback waitCallback, Object state)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate(Object myState)
            {
                try
                {
                    waitCallback.Invoke(myState);
                }
                catch (ThreadAbortException)
                {
                    // Intended blank
                }
#if SILVERLIGHT
                catch (Exception e)
                {
                    Log.Error(e);
                    throw;
                }
#else
                catch (Exception e)
                {
                    Log.Error(e);
                }
#endif
                finally
                {
                    ThreadLocalCleanupController.CleanupThreadLocal();
                }
            }, state);
        }
Esempio n. 3
0
        public void QueueWorkItem(WaitCallback callback, object state = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            new Thread(() =>
            {
                // todo: statistic should be injected as dependency
                CounterStatistic.SetOrleansManagedThread(); // must be called before using CounterStatistic.

                try
                {
                    TrackExecutionStart();
                    callback.Invoke(state);
                }
                catch (Exception exc)
                {
                    HandleExecutionException(exc);
                }
                finally
                {
                    TrackExecutionStop();
                }
            })
            {
                IsBackground = true,
                Name         = Name
            }.Start();
        }
Esempio n. 4
0
        /// <summary>
        /// Executes the application's callback function
        /// </summary>
        /// <remarks>This lets us better control exception handling and make sure the delegate is complete
        /// before we return to our caller while still allowing us to use the thread pool.</remarks>
        private void AsyncTaskExec(object stateInfo)
        {
            try //because we're called from the threadpool we have to catch exceptions.
            {
                //unbundle the state information
                object[]           asyncExecParams = (object[])stateInfo;
                WaitCallback       callBack        = (WaitCallback)asyncExecParams[0];
                AsyncTaskArguments arguments       = (AsyncTaskArguments)asyncExecParams[1];

                if ((callBack == null) || (arguments == null))
                {
                    //we can't execute, this isn't a valid state
                    return;
                }

                callBack.Invoke(arguments);
                CompleteProgress(); //assume if the caller did nothing then we completed.  Ensures we always set our complete state.

                //and set our result.
                TaskResults = arguments.TaskResult;
            }
            catch (Exception ex)
            {
                try //while it seems really unlikely we'll get an exception here, we need to be extra cautious beacuse we're called from the tread pool
                {
                    //set a result..
                    TaskResults = new AsyncTaskResultEventArgs(AsyncTaskResult.Error, ex.Message, ex);
                    CancelProgress(); //if we don't the caller will spin forever.
                }
                catch
                {
                }
            }
        }
Esempio n. 5
0

        
Esempio n. 6
0
        private void ProcessRequests(object o)
        {
            object obj;

            while (m_isRunning)
            {
                try
                {
                    if (!m_jobQueue.TryTake(out obj, m_threadsHoldtime, m_cancelSource.Token))
                    {
                        break;
                    }
                }
                catch
                {
                    break;
                }

                if (!m_isRunning || m_callback == null)
                {
                    break;
                }
                try
                {
                    m_callback.Invoke(obj);
                    obj = null;
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat("[ObjectJob {0}]: Job failed, continuing.  Exception {1}", m_name, e);
                }
            }
            lock (m_mainLock)
                --m_numberThreads;
        }
Esempio n. 7
0
        private void Dispose(bool disposing)
        {
            lock (_disposeLock)
            {
                if (_disposed)
                {
                    return;
                }

                if (disposing)
                {
                    if (_stream1 != null)
                    {
                        _stream1.Dispose();
                    }

                    if (_stream2 != null)
                    {
                        _stream2.Dispose();
                    }
                }

                _disposed = true;
                _onDisposed?.Invoke(this);
            }
        }
Esempio n. 8
0
        public static void ThreadFunc(Object obj)
        {
            //when a thread is started, it already has a task assigned to it.
            WaitCallback task = obj as WaitCallback;

            if (task == null)
            {
                throw new ArgumentException("ThreadFunc must recieve WaitCallback as a parameter!");
            }
            task.Invoke(null);

            //from now on, I'm dequeueing/invoking tasks from the queue.
            while (true)
            {
                task = null;

                lock (threads)
                {
                    lock (queue)
                    {
                        //help a non-empty queue to get rid of its load
                        if (queue.Count > 0)
                        {
                            queue.TryDequeue(out task);
                        }
                    }
                }

                if (task != null)
                {
                    task.Invoke(null);
                }
                else
                {
                    //could not dequeue from the queue, terminate the thread
                    Interlocked.Increment(ref FinishedThreads);
                    return;
                }

                //context switch
                Thread.Sleep(0);
            }
        }
        public static void DispatchSync(this IDispatchQueue queue, object?context, WaitCallback?work)
        {
            TaskCompletionSource <object?> tcs = new TaskCompletionSource <object?>();

            queue.DispatchAsync(context, (context) =>
            {
                work?.Invoke(context);
                tcs.SetResult(null);
            });

            tcs.Task.Wait();
        }
Esempio n. 10
0
 public static void RunAsThread(WaitCallback c, object state = null)
 {
     if (c != null)
     {
         Thread t = new Thread((s) =>
         {
             c.Invoke(state);
         });
         t.Priority = ThreadPriority.Normal;
         t.Start();
     };
 }
Esempio n. 11
0
 public static IEnumerator wait(MonoBehaviour aSender, WaitCallback aCallback, WaitCallBackArgs aArgs)
 {
     if (aArgs != null)
     {
         Debug.Log("Wait - Begin");
         yield return new WaitForSeconds(aArgs.time);
         if (aCallback != null)
         {
             aCallback.Invoke(aSender, aArgs);
         }
         Debug.Log("Wait - End");
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Gets the executor.
 /// </summary>
 /// <value>The executor.</value>
 public void Execute(WaitCallback waitCallback)
 {
     try
     {
         waitCallback.Invoke(null);
     }
     catch (Exception e)
     {
         Console.Error.WriteLine("ThreadPoolExecutor: Event threw exception '{0}'", e.GetType());
         Console.Error.WriteLine("ThreadPoolExecutor: Error message: {0}", e.Message);
         Console.Error.WriteLine(e.StackTrace);
     }
 }
Esempio n. 13
0
 void AsyncTask(object asyncResult)
 {
     if (asyncTask != null)
     {
         asyncTask.Invoke(null);
     }
     if (asyncCallback != null)
     {
         isInvokeAsyncCallback = true;
         asyncCallback.Invoke(asyncResult as IAsyncResult);
     }
     waitHandle.Set();
     isCompleted = true;
 }
Esempio n. 14
0
        } // CloseOnFatalError

        // Called when the SocketHandler is pulled off the pending request queue.
        internal void ProcessRequestNow()
        {
            try
            {
                WaitCallback waitCallback = _dataArrivedCallback;
                if (waitCallback != null)
                {
                    waitCallback.Invoke(this);
                }
            }
            catch (Exception e)
            {
                CloseOnFatalError(e);
            }
        } // ProcessRequestNow
Esempio n. 15
0
            public bool TryDoWork()
            {
                if (mCurrentWork == null)
                {
                    return(false);
                }

                // make a copy because executing the work will likely cause QueueWorkItem to be called
                WaitCallback workCopy = mCurrentWork;

                mCurrentWork = null;

                workCopy.Invoke(mCurrentContext);

                return(true);
            }
Esempio n. 16
0
        private static void UserWorkItem(WaitCallback callback, bool skip_at_app_shutdown)
        {
            IncrementRunningThreadCount();

            try
            {
                if (skip_at_app_shutdown && ShutdownableManager.Instance.IsShuttingDown)
                {
                    Logging.Debug特("SafeThreadPool::QueueUserWorkItem: Breaking out due to application termination");
                    return;
                }

                callback.Invoke(null);
            }
            catch (Exception ex)
            {
                try
                {
                    Logging.Warn(ex, "There has been an exception on the SafeThreadPool context.");
                    if (null != UnhandledException)
                    {
                        UnhandledExceptionEventArgs ueea = new UnhandledExceptionEventArgs(ex, false);
                        UnhandledException(null, ueea);
                    }
                }
                catch (Exception ex2)
                {
                    Logging.Error(ex2, "There was an exception while trying to call back the SafeThreadPool exception callback!");
                }
            }
            finally
            {
                lock (queued_thread_count_lock)
                {
                    queued_thread_count--;
                }
                DecrementRunningThreadCount();
            }
        }
 private static void QueueUserWorkItem_THREAD(WaitCallback callback)
 {
     try
     {
         callback.Invoke(null);
     }
     catch (Exception ex)
     {
         try
         {
             Logging.Warn(ex, "There has been an exception on the SafeThreadPool context.");
             if (null != UnhandledException)
             {
                 UnhandledExceptionEventArgs ueea = new UnhandledExceptionEventArgs(ex, false);
                 UnhandledException(null, ueea);
             }
         }
         catch (Exception ex2)
         {
             Logging.Error(ex2, "There was an exception while trying to call back the SafeThreadPool exception callback!");
         }
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Gets the executor.
        /// </summary>
        /// <value>The executor.</value>
        public void Execute(WaitCallback waitCallback)
        {
            using (_eventMonitor.Acquire())
            {
                while (_isHandlingEvents && (_eventQueueDepth > _maxSize))
                {
                    Thread.Sleep(1);
                }

                if (!_isHandlingEvents)
                {
                    return;
                }
            }

            ThreadPool.QueueUserWorkItem(
                delegate
            {
                try
                {
                    waitCallback.Invoke(null);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("ThreadPoolExecutor: Event threw exception '{0}'", e.GetType());
                    Console.Error.WriteLine("ThreadPoolExecutor: Error message: {0}", e.Message);
                    Console.Error.WriteLine(e.StackTrace);
                }
                finally
                {
                    using (_eventMonitor.Acquire())
                    {
                        _eventQueueDepth++;
                    }
                }
            });
        }
Esempio n. 19
0
        public bool TryQueueWorkItem(WaitCallback callBack, object state)
        {
            if (isDisposing)
            {
                return(true);
            }

            logger.InfoFormat("Queue length: {0}", initialWorkingAndWaitingTasksCount - currentWorkingAndWaitingTasksCount);
            logger.InfoFormat("Working threads: {0}", currentWorkingTasksCount);

            // Check if there is a place to process or queue the task
            if (Interlocked.Decrement(ref currentWorkingAndWaitingTasksCount) < 0)
            {
                // Restore previous value
                Interlocked.Increment(ref currentWorkingAndWaitingTasksCount);
                return(false);
            }

            // Check if task can be processed immediately or must be queued
            if (Interlocked.Decrement(ref currentWorkingTasksCount) < 0)
            {
                // Restore previous value, no task is being executed at the moment.
                Interlocked.Increment(ref currentWorkingTasksCount);
                QueueWorkItem(callBack, state);
                return(true);
            }

            // Queue task for execution
            ThreadPool.QueueUserWorkItem(delegate
            {
                callBack.Invoke(state);
                ProcessQueue();
                Interlocked.Increment(ref currentWorkingTasksCount);
                Interlocked.Increment(ref currentWorkingAndWaitingTasksCount);
            });
            return(true);
        }
Esempio n. 20
0
        public void QueueWorkItem(WaitCallback callback, object state = null)
        {
            new Thread(() =>
            {
#if TRACK_DETAILED_STATS
                if (StatisticsCollector.CollectThreadTimeTrackingStats)
                {
                    threadTracking.OnStartExecution();
                }
#endif
                callback.Invoke(state);

#if TRACK_DETAILED_STATS
                if (StatisticsCollector.CollectThreadTimeTrackingStats)
                {
                    threadTracking.OnStopExecution();
                }
#endif
            })
            {
                IsBackground = true,
                Name         = name
            }.Start();
        }
Esempio n. 21
0
 private void Callback(object _)
 {
     _timer.Dispose();
     _threadPoolWork.Invoke(_state);
 }
 public void QueueUserWorkItem(WaitCallback func)
 {
     func.Invoke(null);
 }
 public void TryQueueWorkItem(WaitCallback callback, object state)
 {
     callback?.Invoke(state);
 }
Esempio n. 24
0
 public void QueueUserWorkItem(WaitCallback func)
 {
     func.Invoke(null);
 }
Esempio n. 25
0
 public void ExecuteWorkItem()
 {
     callback.Invoke(state);
 }
Esempio n. 26
0
 public void Execute()
 {
     ExecutionStart = DateTime.UtcNow;
     callback.Invoke(State);
 }
Esempio n. 27
0
 public void Execute()
 {
     WaitCallback?.Invoke(State);
 }