public void WaitAllT()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = true;

            IWorkItemResult<int>[] wirs = new IWorkItemResult<int>[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] = smartThreadPool.QueueWorkItem(new Func<int, int, int>(System.Math.Min), i, i + 1);
            }

            SmartThreadPool.WaitAll(wirs);

            for (int i = 0; i < wirs.Length; ++i)
            {
                if (!wirs[i].IsCompleted)
                {
                    success = false;
                    break;
                }

                int result = wirs[i].GetResult();
                if (i != result)
                {
                    success = false;
                    break;
                }
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
		public void WaitAny() 
		{ 
			SmartThreadPool smartThreadPool = new SmartThreadPool();
			IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

			bool success = false;

			IWorkItemResult [] wirs = new IWorkItemResult[5];

			for(int i = 0; i < wirs.Length; ++i)
			{
				wirs[i] = 
					workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
			}

			int index = SmartThreadPool.WaitAny(wirs);

			if (wirs[index].IsCompleted)
			{
				int result = (int)wirs[index].GetResult();
				if (1 == result)
				{
					success = true;
				}
			}

			smartThreadPool.Shutdown();

			Assert.IsTrue(success);
		} 
Example #3
0
 public CachedBitmap()
 {
     dispatcher = Dispatcher.CurrentDispatcher;
     _url = "";
     _source = null;
     _workItem = null;
 }
Example #4
0
        public void test()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
            GlobalVar.isCrawling = true;
            //string conn = string.Format(@"Data Source="+System.Environment.CurrentDirectory+"\\data\\{0}", GlobalVar.filename);
            sqlitehelper con = new sqlitehelper(System.Environment.CurrentDirectory + @"\data\" + GlobalVar.filename);
            string sql = "select keyword from Content where flag==0";
            DataTable dt = new DataTable();
            dt = con.GetDataTable(sql);
            IWorkItemResult[] wir = new IWorkItemResult[dt.Rows.Count];
            MessageBox.Show(dt.Rows.Count.ToString());
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //MessageBox.Show(dt.Rows[i]["keyword"].ToString());
                OneWorker one = new OneWorker(dt.Rows[i]["keyword"].ToString());
                ThreadPool.QueueUserWorkItem(one.work, i);

            }

            bool success = SmartThreadPool.WaitAll(
                   wir);

            if (success)
            {
                GlobalVar.isCrawling = false;

            }
            smartThreadPool.Shutdown();
        }
        /// <summary>
        /// Starts the tasks execution.
        /// </summary>
        /// <returns>If has reach the timeout false, otherwise true.</returns>
        public override bool Start()
        {
            base.Start();
            m_threadPool = new SmartThreadPool();

            try
            {
                m_threadPool.MinThreads = MinThreads;
                m_threadPool.MaxThreads = MaxThreads;
                var workItemResults = new IWorkItemResult[Tasks.Count];

                for (int i = 0; i < Tasks.Count; i++)
                {
                    var t = Tasks[i];
                    workItemResults[i] = m_threadPool.QueueWorkItem(new WorkItemCallback(Run), t);
                }

                m_threadPool.Start();

                // Timeout was reach?
                if (!m_threadPool.WaitForIdle(Timeout.TotalMilliseconds > int.MaxValue ? int.MaxValue : Convert.ToInt32(Timeout.TotalMilliseconds)))
                {
                    if (m_threadPool.IsShuttingdown)
                    {
                        return true;
                    }
                    else
                    {
                        m_threadPool.Cancel(true);
                        return false;
                    }
                }

                foreach (var wi in workItemResults)
                {
                    Exception ex;
                    wi.GetResult(out ex);

                    if (ex != null)
                    {
                        throw ex;
                    }
                }

                return true;
            }
            finally
            {
                m_threadPool.Shutdown(true, 1000);
                m_threadPool.Dispose();
                IsRunning = false;
            }
        }
Example #6
0
        private void OneThreadDoneCallback(IWorkItemResult r)
        {
            if (r == null || this.curTaskGroup == null)
            {
                Interlocked.Increment(ref performance.tasksErrored);
            }
            else
            {
                if (r.Exception != null)
                {
                    Interlocked.Increment(ref performance.tasksErrored);
                    this.curTaskGroup.OneTask_Finished(this.showListView, r.Result, TaskStatus.eTaskStatus_Finish_Error);
                }
                if (r.IsCanceled)
                {
                    Interlocked.Increment(ref performance.tasksCancelled);
                    this.curTaskGroup.OneTask_Finished(this.showListView, r.Result, TaskStatus.eTaskStatus_Finish_Cancelled);
                }
                if (r.IsCompleted)
                {
                    if (((ITaskGroupResult)(r.Result)).Status == TaskStatus.eTaskStatus_Finish_Error)
                    {
                        Interlocked.Increment(ref performance.tasksErrored);
                    }
                    else if (((ITaskGroupResult)(r.Result)).Status == TaskStatus.eTaskStatus_Finish_Cancelled)
                    {
                        Interlocked.Increment(ref performance.tasksCancelled);
                    }
                    else
                    {
                        Interlocked.Increment(ref performance.tasksCompleted);
                    }
                    this.curTaskGroup.OneTask_Finished(this.showListView, r.Result, TaskStatus.eTaskStatus_Finish_Suceessed);
                }
            }

            if (performance.tasksErrored + performance.tasksCancelled + performance.tasksCompleted >= performance.tasksGenerated)
            {
                GlobalVar.Instance.logger.Info("全部任务消费完毕.");
                isWorkerThreadRunning = false;
                NoticeWorkerThreadStop();
                return;
            }
        }
        public void WaitForIdleWithCancel()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool(10 * 1000, 1, 1);
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(2);

            _x = 0;

            IWorkItemResult wir1 = workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), 1000);
            IWorkItemResult wir2 = workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), 1000);
            IWorkItemResult wir3 = workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), 1000);

            while (0 == _x)
            {
                Thread.Sleep(10);
            }

            //Console.WriteLine("{0}: Cancelling WIG", DateTime.Now.ToLongTimeString());
            workItemsGroup.Cancel();

            // At this point:
            // The first work item is running
            // The second work item is cancelled, but waits in the STP queue
            // The third work item is cancelled.

            Assert.AreEqual(1, _x);

            Assert.IsTrue(wir2.IsCanceled);

            Assert.IsTrue(wir3.IsCanceled);

            // Make sure the workItemsGroup is still idle
            Assert.IsFalse(workItemsGroup.IsIdle);

            //Console.WriteLine("{0}: Waiting for 1st result", DateTime.Now.ToLongTimeString());
            wir1.GetResult();

            Assert.AreEqual(2, _x);

            bool isIdle = workItemsGroup.WaitForIdle(100);

            Assert.IsTrue(isIdle);

            smartThreadPool.Shutdown();
        }
Example #8
0
        //[ExpectedException(typeof(WorkItemCancelException))]
        public void CancelCancelledWorkItemAbort()
        {
            Assert.ThrowsException <WorkItemCancelException>(() =>
            {
                ManualResetEvent waitToStart = new ManualResetEvent(false);

                STP stp             = new STP();
                IWorkItemResult wir = stp.QueueWorkItem(
                    state =>
                {
                    waitToStart.Set();
                    while (true)
                    {
                        Thread.Sleep(1000);
                    }
#pragma warning disable CS0162 // Unreachable code detected
                    return(null);

#pragma warning restore CS0162 // Unreachable code detected
                }
                    );

                waitToStart.WaitOne();

                wir.Cancel(false);

                Assert.IsTrue(wir.IsCanceled);

                bool completed = stp.WaitForIdle(1000);

                Assert.IsFalse(completed);

                wir.Cancel(true);

                try
                {
                    wir.GetResult();
                }
                finally
                {
                    stp.Shutdown();
                }
            });
        }
Example #9
0
 public void Reset(int delay = -1)
 {
     if ((this._current == null) || this._current.IsCompleted || this._current.IsCanceled)
     {
         //AsmDudeToolsStatic.Output_INFO("Delay:Reset: starting a new timer");
         this._nResets = 0;
         this._current = this._threadPool.QueueWorkItem(this.Timer, delay);
     }
     else
     {
         if (this._nResets < this._maxResets)
         {
             //AsmDudeToolsStatic.Output_INFO("Delay:Reset: resetting the timer: "+this._nResets);
             this._current.Cancel(true);
             this._nResets++;
             this._current = this._threadPool.QueueWorkItem(this.Timer, delay);
         }
     }
 }
        public void DoWork()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            IWorkItemResult <double> wir = smartThreadPool.QueueWorkItem(new Func <double, double, double>(DoDiv), 10.0, 0.0);

            try
            {
                double result = wir.Result;
            }
            // Catch the exception that Result threw
            catch (WorkItemResultException e)
            {
                // Dump the inner exception which DoDiv threw
                Debug.WriteLine(e.InnerException);
            }

            smartThreadPool.Shutdown();
        }
        public void Timeout()
        {
            Assert.Throws <WorkItemTimeoutException>(() =>
            {
                SmartThreadPool smartThreadPool = new SmartThreadPool();

                IWorkItemResult wir =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);

                try
                {
                    wir.GetResult(500, true);
                }
                finally
                {
                    smartThreadPool.Shutdown();
                }
            });
        }
        public void BlockingCall()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = false;

            IWorkItemResult wir =
                smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);

            if (!wir.IsCompleted)
            {
                int result = (int)wir.GetResult();
                success = (1 == result);
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #13
0
        public void CancelInQueueWorkItem()
        {
            Assert.ThrowsException <WorkItemCancelException>(() =>
            {
                STPStartInfo stpStartInfo = new STPStartInfo {
                    StartSuspended = true
                };

                STP stp             = new STP(stpStartInfo);
                IWorkItemResult wir = stp.QueueWorkItem(arg => null);

                wir.Cancel();

                Assert.IsTrue(wir.IsCanceled);

                try { wir.GetResult(); }
                finally { stp.Shutdown(); }
            });
        }
        public void FuncT()
        {
            STP stp = new STP();
            IWorkItemResult <int> wir =
                stp.QueueWorkItem(new Func <int, int>(Function), 1);

            int y = wir.GetResult();

            Assert.AreEqual(y, 2);

            try
            {
                wir.GetResult();
            }
            finally
            {
                stp.Shutdown();
            }
        }
Example #15
0
        public void WaitAllWithTimeoutFailure()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            bool timeout = !SmartThreadPool.WaitAll(wirs, 10, true);
            bool success = timeout;

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #16
0
        public void FuncT()
        {
            SmartThreadPool       stp = new SmartThreadPool();
            IWorkItemResult <int> wir =
                stp.QueueWorkItem(new Func <int, int>(f), 1);

            int y = wir.GetResult();

            Assert.AreEqual(y, 2);

            try
            {
                wir.GetResult();
            }
            finally
            {
                stp.Shutdown();
            }
        }
        public static void UpdatePrice()
        {
            var list = WayBillController.GetUpdatePriceWayBillList();

            if (list == null || list.Count <= 0)
            {
                return;
            }
            if (ismultithreading.ToLowerInvariant() == "no")
            {
                //单线程
                foreach (var model in list)
                {
                    if (!WayBillController.UpdatePriceWayBill(FreightController.GetFreightPrice(model),
                                                              model.WayBillNumber, model.ReceivingExpenseID))
                    {
                        Log.Error(string.Format("运单号:{0}更新错误!", model.WayBillNumber));
                    }
                }
            }
            else if (ismultithreading.ToLowerInvariant() == "yes")
            {
                //多线程
                if (minThreads > maxThreads)
                {
                    maxThreads = minThreads;
                }
                var threadPool = new SmartThreadPool {
                    MaxThreads = maxThreads < 1 ? 1 : maxThreads, MinThreads = minThreads < 1 ? 1 : minThreads
                };
                var pendingWorkItems = new IWorkItemResult[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    pendingWorkItems[i] = threadPool.QueueWorkItem(new WorkItemCallback(MUpdatePrice), list[i]);
                }

                if (SmartThreadPool.WaitAll(pendingWorkItems))
                {
                    threadPool.Shutdown();
                }
            }
        }
        /// <summary>
        /// Starts the tasks execution.
        /// </summary>
        /// <returns>If has reach the timeout false, otherwise true.</returns>
        public override bool Start()
        {
            base.Start();
            m_threadPool = new SmartThreadPool();

            try
            {
                m_threadPool.MinThreads = MinThreads;
                m_threadPool.MaxThreads = MaxThreads;
                var workItemResults = new IWorkItemResult[Tasks.Count];

                for (int i = 0; i < Tasks.Count; i++)
                {
                    var t = Tasks[i];
                    workItemResults[i] = m_threadPool.QueueWorkItem(new WorkItemCallback(Run), t);
                }

                m_threadPool.Start();

                if (!m_threadPool.WaitForIdle(Timeout.TotalMilliseconds > int.MaxValue ? int.MaxValue : Convert.ToInt32(Timeout.TotalMilliseconds)))
                {
                    return(false);
                }

                foreach (var wi in workItemResults)
                {
                    Exception ex;
                    wi.GetResult(out ex);

                    if (ex != null)
                    {
                        throw ex;
                    }
                }

                return(true);
            }
            finally {
                m_threadPool.Shutdown(true, 1000);
                m_threadPool.Dispose();
            }
        }
Example #19
0
        public void CancelInQueueWorkItem()
        {
            Assert.Throws <WorkItemCancelException>(() =>
            {
                STPStartInfo stpStartInfo   = new STPStartInfo();
                stpStartInfo.StartSuspended = true;

                bool hasRun = false;

                SmartThreadPool stp = new SmartThreadPool(stpStartInfo);
                IWorkItemResult wir = stp.QueueWorkItem(
                    new WorkItemInfo()
                {
                    Timeout = 500
                },
                    state =>
                {
                    hasRun = true;
                    return(null);
                });

                Assert.IsFalse(wir.IsCanceled);

                Thread.Sleep(2000);

                Assert.IsTrue(wir.IsCanceled);

                stp.Start();
                stp.WaitForIdle();

                Assert.IsFalse(hasRun);

                try
                {
                    wir.GetResult();
                }
                finally
                {
                    stp.Shutdown();
                }
            });
        }
Example #20
0
        public void WaitAllWithTimeoutSuccess()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            bool timeout = !SmartThreadPool.WaitAll(wirs, 1500, true);
            bool success = !timeout;

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
        public void WaitAllWithTimeoutFailure()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for(int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            bool timeout = !SmartThreadPool.WaitAll(wirs, 10, true);
            bool success = timeout;

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #22
0
        /// <summary>
        /// Break |list| into slices of at least |minChunkSize| and schedule them on a thread pool.
        /// |action| is executed on each slice.
        /// </summary>
        public static void ParallelDo <T>(this IList <T> list, Action <IEnumerable <T> > action,
                                          int minChunkSize           = DefaultMinChunkSize,
                                          SmartThreadPool threadPool = null)
        {
            threadPool = threadPool ?? DefaultSmartThreadPool;
            const int maxHandles = 64; // Maximum for WaitHandle
            var       count      = list.Count();

            if (count == 0)
            {
                return;
            }
            // WaitAll() does not support waiting for multiple handles on STA threads.
            if (count < minChunkSize * 2)
            {
                action(list);
                return;
            }
            var parallelism        = Math.Min(maxHandles, Math.Max(1, count / minChunkSize));
            var effectiveChunkSize = count / parallelism;
            var items = new IWorkItemResult[parallelism];

            for (var offset = 0; offset < parallelism; offset++)
            {
                var start = effectiveChunkSize * offset;
                var chunk = list.Skip(start).Take(offset == parallelism - 1 ? count - start : effectiveChunkSize);
                items[offset] = threadPool.QueueWorkItem(() => action(chunk));
            }
            try
            {
                SmartThreadPool.WaitAll(items);
            }
            catch (ThreadInterruptedException ex)
            {
                foreach (var item in items)
                {
                    item.Cancel();
                }
                throw;
            }
        }
Example #23
0
        //[ExpectedException(typeof(WorkItemCancelException))]
        public void CancelCancelledWorkItemAbort()
        {
            Assert.Throws <WorkItemCancelException>(() =>
            {
                ManualResetEvent waitToStart = new ManualResetEvent(false);

                SmartThreadPool stp = new SmartThreadPool();
                IWorkItemResult wir = stp.QueueWorkItem(
                    state =>
                {
                    waitToStart.Set();
                    while (true)
                    {
                        Thread.Sleep(1000);
                    }
                    //return null;
                }
                    );

                waitToStart.WaitOne();

                wir.Cancel(false);

                Assert.IsTrue(wir.IsCanceled);

                bool completed = stp.WaitForIdle(1000);

                Assert.IsFalse(completed);

                wir.Cancel(true);

                try
                {
                    wir.GetResult();
                }
                finally
                {
                    stp.Shutdown();
                }
            });
        }
Example #24
0
        /// <summary>
        /// 程序入口  朱旺  2018.4.23 add
        /// </summary>
        public void SyncData()
        {
            int Count = GetCount();

            if (Count != 0)
            {
                int Page = Count % Row == 0 ? Count / Row : Count / Row + 1; //第一步计算该开多少个线程
                DeleteTable();                                               //第二步清空表数据
                //第三步多线程执行方法
                using (SmartThreadPool smartThreadPool = new SmartThreadPool())
                {
                    List <IWorkItemResult> wirs = new List <IWorkItemResult>();
                    for (int i = 1; i <= Page; i++)
                    {
                        IWorkItemResult wir = smartThreadPool.QueueWorkItem(new WorkItemCallback(@delegate), i);
                        wirs.Add(wir);
                    }
                    SmartThreadPool.WaitAll(wirs.ToArray());
                }
            }
        }
Example #25
0
 //--------------------------------------------------------------------------------
 /// <summary>
 /// Queues this object in the thread pool.
 /// </summary>
 /// <param name="pool"></param>
 /// <returns></returns>
 public IWorkItemResult QueueProcess(SmartThreadPool pool)
 {
     workItemResult = null;
     if (pool != null)
     {
         try
         {
             if (threadPoolState == null)
             {
                 threadPoolState = new object();
             }
             workItemResult = pool.QueueWorkItem(new WorkItemCallback(this.SyncFiles), WorkItemPriority.Normal);
         }
         catch (Exception ex)
         {
             ex.Data.Add("Name", this.Name);
             throw ex;
         }
     }
     return(workItemResult);
 }
Example #26
0
#pragma warning restore 0618

        private void backgroundMonitor()
        {
#if DEBUG
            if (Debugger.IsAttached)
            {
                return;
            }
#endif

            while (!ConfigManager.dDisablePerformanceLogging)
            {
                if (timekeepingStopWatch.GetElapsedMillisecondsPrecise() - stopwatchConsumptionTime > spikeTime && backgroundMonitorStackTrace == null)
                {
                    backgroundMonitorStackTrace = safelyGetStackTrace(GameBase.MainThread);
                }

                Thread.Sleep(1);
            }

            backgroundMonitorThread = null;
        }
Example #27
0
        /// <summary>
        /// This is the main method of the Overlay thread. It reads messages from the
        /// MessageQueue and processes them.
        /// </summary>
        public void EventLoop()
        {
            try
            {
                while (!exit)
                {
                    QueueEntry p = queue.Remove();
                    if (p != null)
                    {
                        ThreadLocalEvent tle = new ThreadLocalEvent();
                        p.message.threadLocalEvent = tle;

                        IWorkItemResult result = m_STP.QueueWorkItem(
                            new WorkItemCallback(RaiseEventByThreadPool), p);

                        tle.WorkItemResult = result;
                    }
                }
            }
            catch (ObjectDisposedException) { }
        }
Example #28
0
        public void WaitAnyWithTimeoutFailure()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            int index = SmartThreadPool.WaitAny(wirs, 10, true);

            bool success = (index == WaitHandle.WaitTimeout);

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #29
0
        public void TimeoutCompletedWorkItem()
        {
            SmartThreadPool stp = new SmartThreadPool();
            IWorkItemResult wir =
                stp.QueueWorkItem(
                    new WorkItemInfo()
            {
                Timeout = 500
            },
                    state => 1);

            stp.WaitForIdle();

            Assert.AreEqual(wir.GetResult(), 1);

            Thread.Sleep(1000);

            Assert.AreEqual(wir.GetResult(), 1);

            stp.Shutdown();
        }
        //IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback);
        public static void TestQueueWorkItemInfoCall(IWorkItemsGroup wig)
        {
            WorkItemInfo wii = new WorkItemInfo();

            wii.CallToPostExecute           = CallToPostExecute.Never;
            wii.DisposeOfStateObjects       = true;
            wii.PostExecuteWorkItemCallback = delegate(IWorkItemResult w) { };
            wii.UseCallerCallContext        = true;
            wii.UseCallerHttpContext        = true;
            wii.WorkItemPriority            = WorkItemPriority.Highest;

            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii);

            IWorkItemResult wir = wig.QueueWorkItem(wii, wiic.CompareWorkItemInfo);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
        }
Example #31
0
        /// <summary>Constructor</summary>
        public CodeFoldingTagger(
            ITextBuffer buffer,
            ITagAggregator <AsmTokenTag> aggregator,
            ErrorListProvider errorListProvider)
        {
            //AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:constructor", this.ToString()));
            this.buffer_            = buffer ?? throw new ArgumentNullException(nameof(buffer));
            this.aggregator_        = aggregator ?? throw new ArgumentNullException(nameof(aggregator));
            this.errorListProvider_ = errorListProvider ?? throw new ArgumentNullException(nameof(errorListProvider));

            this.snapshot_ = buffer.CurrentSnapshot;
            this.regions_  = new List <Region>();

            AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:constructor; number of lines in file = {1}", this.ToString(), buffer.CurrentSnapshot.LineCount));

            this.enabled_ = true;

            if (buffer.CurrentSnapshot.LineCount >= AsmDudeToolsStatic.MaxFileLines)
            {
                this.enabled_ = false;
                AsmDudeToolsStatic.Output_WARNING(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:CodeFoldingTagger; file {1} contains {2} lines which is more than maxLines {3}; switching off code folding", this.ToString(), AsmDudeToolsStatic.GetFilename(buffer), buffer.CurrentSnapshot.LineCount, AsmDudeToolsStatic.MaxFileLines));
            }

            if (this.enabled_)
            {
                this.delay_             = new Delay(AsmDudePackage.MsSleepBeforeAsyncExecution, 10, AsmDudeTools.Instance.Thread_Pool);
                this.delay_.Done_Event += (o, i) =>
                {
                    if ((this.thread_Result_ != null) && (!this.thread_Result_.IsCanceled))
                    {
                        this.thread_Result_.Cancel();
                    }
                    this.thread_Result_ = AsmDudeTools.Instance.Thread_Pool.QueueWorkItem(this.Parse);
                };

                this.delay_.Reset();
                this.buffer_.ChangedLowPriority += this.Buffer_Changed;
            }
        }
Example #32
0
        public void WaitAll()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            bool success = true;

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            SmartThreadPool.WaitAll(wirs);

            for (int i = 0; i < wirs.Length; ++i)
            {
                if (!wirs[i].IsCompleted)
                {
                    success = false;
                    break;
                }
                else
                {
                    int result = (int)wirs[i].GetResult();
                    if (1 != result)
                    {
                        success = false;
                        break;
                    }
                }
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #33
0
        public void CancelCanceledWorkItem()
        {
            Assert.ThrowsException <WorkItemCancelException>(() =>
            {
                STPStartInfo stpStartInfo = new STPStartInfo {
                    StartSuspended = true
                };

                STP stp             = new STP(stpStartInfo);
                IWorkItemResult wir = stp.QueueWorkItem(state => null);

                int counter = 0;

                wir.Cancel();

                try
                {
                    wir.GetResult();
                }
                catch (WorkItemCancelException ce)
                {
                    ce.GetHashCode();
                    ++counter;
                }

                Assert.AreEqual(counter, 1);

                wir.Cancel();

                try
                {
                    wir.GetResult();
                }
                finally
                {
                    stp.Shutdown();
                }
            });
        }
Example #34
0
        // Can't run this test, StackOverflowException crashes the application and can't be catched and ignored
        //[TestMethod]
        public void NotTestThreadsMaxStackSize()
        {
            STPStartInfo stpStartInfo = new STPStartInfo()
            {
                MaxStackSize = 64 * 1024,
            };

            STP stp = new STP(stpStartInfo);

            stp.Start();

            IWorkItemResult <bool> wir = stp.QueueWorkItem(() => AllocateBufferOnStack(10 * 1024));

            bool result = wir.GetResult();

            Assert.IsTrue(result);

            wir = stp.QueueWorkItem(() => AllocateBufferOnStack(1000 * 1024));

            result = wir.GetResult();
            Assert.IsFalse(result);
        }
Example #35
0
        public void WaitAnyWithTimeoutSuccess()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = true;

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            int index = SmartThreadPool.WaitAny(wirs, 1500, true);

            success = (index != WaitHandle.WaitTimeout);

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #36
0
        public void CancelInQueueWorkItem()
        {
            STPStartInfo stpStartInfo = new STPStartInfo();

            stpStartInfo.StartSuspended = true;

            SmartThreadPool stp = new SmartThreadPool(stpStartInfo);
            IWorkItemResult wir = stp.QueueWorkItem(arg => null);

            wir.Cancel();

            Assert.IsTrue(wir.IsCanceled);

            try
            {
                wir.GetResult();
            }
            finally
            {
                stp.Shutdown();
            }
        }
        public void WaitAll()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = true;

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for(int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            SmartThreadPool.WaitAll(wirs);

            for(int i = 0; i < wirs.Length; ++i)
            {
                if (!wirs[i].IsCompleted)
                {
                    success = false;
                    break;
                }
                else
                {
                    int result = (int)wirs[i].GetResult();
                    if (1 != result)
                    {
                        success = false;
                        break;
                    }
                }
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
		public void DoWork() 
		{ 
			SmartThreadPool smartThreadPool = new SmartThreadPool();

			IWorkItemResult wir1 = 
				smartThreadPool.QueueWorkItem(new 
				WorkItemCallback(this.DoSomeWork1), null);

			IWorkItemResult wir2 = 
				smartThreadPool.QueueWorkItem(new 
				WorkItemCallback(this.DoSomeWork2), null);

			IWorkItemResult [] wirs = new IWorkItemResult [] { wir1, wir2 };

			int index = SmartThreadPool.WaitAny(wirs);

			if (index != WaitHandle.WaitTimeout)
			{
				int result = (int)wirs[index].Result;
			}

			smartThreadPool.Shutdown();
		} 
 /// <summary>
 /// Waits for any of the work items in the specified array to complete, cancel, or timeout
 /// </summary>
 /// <param name="workItemResults">Array of work item result objects</param>
 /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
 /// <param name="exitContext">
 /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. 
 /// </param>
 /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
 /// <returns>
 /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
 /// </returns>
 public static int WaitAny(
     IWorkItemResult [] workItemResults,  
     int millisecondsTimeout,
     bool exitContext,
     WaitHandle cancelWaitHandle)
 {
     return WorkItem.WaitAny(workItemResults, millisecondsTimeout, exitContext, cancelWaitHandle);
 }
		private void DoSomePostExecuteWork(IWorkItemResult wir)
		{ 
			PostExecuteResult postExecuteResult = wir.State as PostExecuteResult;
			postExecuteResult.wh.Set();
		}
        public void WaitAnyT()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = false;

            IWorkItemResult<int>[] wirs = new IWorkItemResult<int>[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] = smartThreadPool.QueueWorkItem(new Func<int, int, int>(Math.Max), i, i - 1);
            }

            int index = SmartThreadPool.WaitAny(wirs);

            if (wirs[index].IsCompleted)
            {
                int result = wirs[index].GetResult();
                if (index == result)
                {
                    success = true;
                }
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #42
0
        public Object DoOnRezScriptQueue(Object dummy)
        {
            if (m_InitialStartup)
            {
                m_InitialStartup = false;
                System.Threading.Thread.Sleep(15000);
                lock (m_CompileQueue) 
                {
                    if (m_CompileQueue.Count==0)
                        // No scripts on region, so won't get triggered later
                        // by the queue becoming empty so we trigger it here
                        m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
                }
            }

            Object o;
            lock (m_CompileQueue)
            {
                o = m_CompileQueue.Dequeue();
                if (o == null)
                {
                    m_CurrentCompile = null;
                    return null;
                }
            }

            DoOnRezScript(o);

            lock (m_CompileQueue)
            {
                if (m_CompileQueue.Count > 0)
                {
                    m_CurrentCompile = m_ThreadPool.QueueWorkItem(
                            new WorkItemCallback(this.DoOnRezScriptQueue),
                            new Object[0]);
                }
                else
                {
                    m_CurrentCompile = null;
                    m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount, 
                                                                        m_ScriptErrorMessage);
                    m_ScriptFailCount = 0;
                }
            }
            return null;
        }
Example #43
0
        public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
        {
            if (script.StartsWith("//MRM:"))
                return;

            List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());

            List<string> names = new List<string>();
            foreach (IScriptModule m in engines)
                names.Add(m.ScriptEngineName);

            int lineEnd = script.IndexOf('\n');

            if (lineEnd > 1)
            {
                string firstline = script.Substring(0, lineEnd).Trim();

                int colon = firstline.IndexOf(':');
                if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
                {
                    string engineName = firstline.Substring(2, colon-2);

                    if (names.Contains(engineName))
                    {
                        engine = engineName;
                        script = "//" + script.Substring(script.IndexOf(':')+1);
                    }
                    else
                    {
                        if (engine == ScriptEngineName)
                        {
                            SceneObjectPart part =
                                    m_Scene.GetSceneObjectPart(
                                    localID);
                         
                            TaskInventoryItem item =
                                    part.Inventory.GetInventoryItem(itemID);

                            ScenePresence presence = 
                                    m_Scene.GetScenePresence(
                                    item.OwnerID);

                            if (presence != null)
                            {
                               presence.ControllingClient.SendAgentAlertMessage(
                                        "Selected engine unavailable. "+
                                        "Running script on "+
                                        ScriptEngineName,
                                        false);
                            }
                        }
                    }
                }
            }

            if (engine != ScriptEngineName)
                return;

            Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};

            if (stateSource == (int)StateSource.ScriptedRez)
            {
                DoOnRezScript(parms);
            }
            else
            {
                lock (m_CompileQueue)
                {
                    m_CompileQueue.Enqueue(parms);

                    if (m_CurrentCompile == null)
                    {
                        m_CurrentCompile = m_ThreadPool.QueueWorkItem(
                                new WorkItemCallback(this.DoOnRezScriptQueue),
                                new Object[0]);
                    }
                }
            }
        }
Example #44
0
		/// <summary>
		/// Fill an array of wait handles with the work items wait handles.
		/// </summary>
		/// <param name="workItemResults">An array of work item results</param>
		/// <param name="waitHandles">An array of wait handles to fill</param>
		private static void GetWaitHandles(
			IWorkItemResult [] workItemResults,
			WaitHandle [] waitHandles)
		{
			for(int i = 0; i < workItemResults.Length; ++i)
			{
				WorkItemResult wir = workItemResults[i] as WorkItemResult;
				Debug.Assert(null != wir, "All workItemResults must be WorkItemResult objects");

				waitHandles[i] = wir.GetWorkItem().GetWaitHandle();
			}
		}
Example #45
0
		/// <summary>
		/// Release the work items' wait handles
		/// </summary>
		/// <param name="workItemResults">An array of work item results</param>
		private static void ReleaseWaitHandles(IWorkItemResult [] workItemResults)
		{
			for(int i = 0; i < workItemResults.Length; ++i)
			{
				WorkItemResult wir = workItemResults[i] as WorkItemResult;

				wir.GetWorkItem().ReleaseWaitHandle();
			}
		}
Example #46
0
		/// <summary>
		/// Waits for any of the work items in the specified array to complete, cancel, or timeout
		/// </summary>
		/// <param name="workItemResults">Array of work item result objects</param>
		/// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
		/// <param name="exitContext">
		/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. 
		/// </param>
		/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
		/// <returns>
		/// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
		/// </returns>
		internal static int WaitAny(			
			IWorkItemResult [] workItemResults,
			int millisecondsTimeout,
			bool exitContext,
			WaitHandle cancelWaitHandle)
		{
			WaitHandle [] waitHandles = null;

			if (null != cancelWaitHandle)
			{
				waitHandles = new WaitHandle[workItemResults.Length+1];
				GetWaitHandles(workItemResults, waitHandles);
				waitHandles[workItemResults.Length] = cancelWaitHandle;
			}
			else
			{
				waitHandles = new WaitHandle[workItemResults.Length];
				GetWaitHandles(workItemResults, waitHandles);
			}

			int result = WaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext);

			// Treat cancel as timeout
			if (null != cancelWaitHandle)
			{
				if (result == workItemResults.Length)
				{
					result = WaitHandle.WaitTimeout;
				}
			}

			ReleaseWaitHandles(workItemResults);

			return result;
		}
Example #47
0
        public Object DoOnRezScriptQueue(Object dummy)
        {
            if (m_InitialStartup)
            {
                m_InitialStartup = false;
                System.Threading.Thread.Sleep(15000);

                if (m_CompileQueue.Count == 0)
                {
                    // No scripts on region, so won't get triggered later
                    // by the queue becoming empty so we trigger it here
                    m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
                }
            }

            object[] o;
            while (m_CompileQueue.Dequeue(out o))
                DoOnRezScript(o);

            // NOTE: Despite having a lockless queue, this lock is required
            // to make sure there is never no compile thread while there
            // are still scripts to compile. This could otherwise happen
            // due to a race condition
            //
            lock (m_CompileQueue)
            {
                m_CurrentCompile = null;
            }
            m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
                                                                m_ScriptErrorMessage);
            m_ScriptFailCount = 0;

            return null;
        }
Example #48
0
        /* private static void PropertyChangedCallback(DependencyObject dependencyObject,
                                                    DependencyPropertyChangedEventArgs
                                                        dependencyPropertyChangedEventArgs)*/
        private void load_image(String url)
        {
            if (_workItem != null && !_workItem.IsCompleted)
                return;
            _workItem = StaticInstance.ThreadPool.QueueWorkItem(() =>
                                                                {
                                                                    // var instance = dependencyObject as CachedBitmap;
                                                                    //SetLoading(true, instance);

                                                                    HashAlgorithm hashAlg = new SHA512CryptoServiceProvider();

                                                                    Crc64 crc64 = new Crc64(Crc64Iso.Iso3309Polynomial);

                                                                    string urlcrc64 =
                                                                        BitConverter.ToString(crc64.ComputeHash(Encoding.ASCII.GetBytes(url)))
                                                                                    .Replace("-", "").ToLower();

                                                                    string cachePath = Path.Combine(Path.GetTempPath(), "sjupdater", "imagechache");
                                                                    string filepath = Path.Combine(cachePath, urlcrc64.ToLower() + ".imagecache");

                                                                    Action downloadAndSetAndCache = () =>
                                                                                                    {
                                                                                                        using (MemoryStream ms = DownloadData(url))
                                                                                                        {
                                                                                                            if (ms == null) return;

                                                                                                            BitmapSource bitmapSource = BitmapImageFromStream(ms);
                                                                                                            dispatcher.Invoke(() =>
                                                                                                                              {

                                                                                                                                  ImageSource = bitmapSource;
                                                                                                                              });

                                                                                                            CacheData(filepath, ms, hashAlg);
                                                                                                        }
                                                                                                    };

                                                                    if (File.Exists(filepath))
                                                                    {
                                                                        byte[] cacheHash;

                                                                        MemoryStream ms = GetCachedData(filepath, hashAlg, out cacheHash);
                                                                        BitmapImage image = BitmapImageFromStream(ms);
                                                                        //  SetLoading(false, instance);

                                                                        dispatcher.Invoke(() =>
                                                                                          {
                                                                                              ImageSource = image;
                                                                                          });

                                                                        MemoryStream data = DownloadData(url);
                                                                        if (data == null)
                                                                            return;

                                                                        byte[] downloadHash = new byte[hashAlg.HashSize / 8];
                                                                        downloadHash = hashAlg.ComputeHash(data);

                                                                        if (!cacheHash.Memcmp(downloadHash))
                                                                        {
                                                                            // SetLoading(true, instance);
                                                                            downloadAndSetAndCache();
                                                                            //  SetLoading(false, instance);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        // SetLoading(true, instance);
                                                                        downloadAndSetAndCache();
                                                                        //  SetLoading(false, instance);
                                                                    }
                                                                }, true, ThreadPriority.Lowest);
        }
Example #49
0
        private void RequestCompleted(IWorkItemResult workItem)
        {
            lock (_currentRequests)
            {
                UUID userId = (UUID)workItem.State;

                IWorkItemResult currentRequest;
                if (_currentRequests.TryGetValue(userId, out currentRequest))
                {
                    if (currentRequest == workItem)
                    {
                        _currentRequests.Remove(userId);
                    }
                }
            }
        }
 private static void PostExecuteWorkItemCallback(IWorkItemResult wir)
 {
     //TODO 线程结束时调用
     logger.Debug("上传线程结束");
 }
 private void DoPostExecute(IWorkItemResult wir)
 {
 }
Example #52
0
 public XWorkItem(IWorkItemResult w)
 {
     wr = w;
 }
Example #53
0
	    private void RegisterToWorkItemCompletion(IWorkItemResult wir)
		{
			IInternalWorkItemResult iwir = (IInternalWorkItemResult)wir;
			iwir.OnWorkItemStarted += OnWorkItemStartedCallback;
			iwir.OnWorkItemCompleted += OnWorkItemCompletedCallback;
		}
Example #54
0
        public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
        {
//            m_log.DebugFormat(
//                "[XEngine]: OnRezScript event triggered for script {0}, startParam {1}, postOnRez {2}, engine {3}, stateSource {4}, script\n{5}",
//                 itemID, startParam, postOnRez, engine, stateSource, script);

            if (script.StartsWith("//MRM:"))
                return;

            List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());

            List<string> names = new List<string>();
            foreach (IScriptModule m in engines)
                names.Add(m.ScriptEngineName);

            int lineEnd = script.IndexOf('\n');

            if (lineEnd > 1)
            {
                string firstline = script.Substring(0, lineEnd).Trim();

                int colon = firstline.IndexOf(':');
                if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
                {
                    string engineName = firstline.Substring(2, colon - 2);

                    if (names.Contains(engineName))
                    {
                        engine = engineName;
                        script = "//" + script.Substring(colon + 1);
                    }
                    else
                    {
                        if (engine == ScriptEngineName)
                        {
                            // If we are falling back on XEngine as the default engine, then only complain to the user
                            // if a script language has been explicitly set and it's one that we recognize or there are
                            // no non-whitespace characters after the colon.
                            //
                            // If the script is
                            // explicitly not allowed or the script is not in LSL then the user will be informed by a later compiler message.
                            //
                            // If the colon ends the line then we'll risk the false positive as this is more likely
                            // to signal a real scriptengine line where the user wants to use the default compile language.
                            //
                            // This avoids the overwhelming number of false positives where we're in this code because
                            // there's a colon in a comment in the first line of a script for entirely
                            // unrelated reasons (e.g. vim settings).
                            //
                            // TODO: A better fix would be to deprecate simple : detection and look for some less likely
                            // string to begin the comment (like #! in unix shell scripts).
                            bool warnRunningInXEngine = false;
                            string restOfFirstLine = firstline.Substring(colon + 1);

                            // FIXME: These are hardcoded because they are currently hardcoded in Compiler.cs
                            if (restOfFirstLine.StartsWith("c#")
                                || restOfFirstLine.StartsWith("vb")
                                || restOfFirstLine.StartsWith("lsl")
                                || restOfFirstLine.StartsWith("js")
                                || restOfFirstLine.StartsWith("yp")
                                || restOfFirstLine.Length == 0)
                                warnRunningInXEngine = true;

                            if (warnRunningInXEngine)
                            {
                                SceneObjectPart part =
                                        m_Scene.GetSceneObjectPart(
                                        localID);
                             
                                TaskInventoryItem item =
                                        part.Inventory.GetInventoryItem(itemID);
    
                                ScenePresence presence = 
                                        m_Scene.GetScenePresence(
                                        item.OwnerID);
    
                                if (presence != null)
                                {
                                   presence.ControllingClient.SendAgentAlertMessage(
                                            "Selected engine unavailable. "+
                                            "Running script on "+
                                            ScriptEngineName,
                                            false);
                                }
                            }
                        }
                    }
                }
            }

            if (engine != ScriptEngineName)
                return;

            // If we've seen this exact script text before, use that reference instead
            if (m_uniqueScripts.ContainsKey(script))
                script = m_uniqueScripts[script];
            else
                m_uniqueScripts[script] = script;

            Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};

            if (stateSource == (int)StateSource.ScriptedRez)
            {
                lock (m_CompileDict)
                {
                    m_CompileDict[itemID] = 0;
                }

                DoOnRezScript(parms);
            }
            else
            {
                m_CompileQueue.Enqueue(parms);
                lock (m_CompileDict)
                {
                    m_CompileDict[itemID] = 0;
                }

//                m_log.DebugFormat("[XEngine]: Added script {0} to compile queue", itemID);

                if (m_CurrentCompile == null)
                {
                    // NOTE: Although we use a lockless queue, the lock here
                    // is required. It ensures that there are never two
                    // compile threads running, which, due to a race
                    // conndition, might otherwise happen
                    //
                    lock (m_CompileQueue)
                    {
                        if (m_CurrentCompile == null)
                            m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
                    }
                }
            }
        }
        public void WaitAllWithTimeoutSuccess()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for(int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            bool timeout = !SmartThreadPool.WaitAll(wirs, 1500, true);
            bool success = !timeout;

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #56
0
        public Object DoOnRezScriptQueue(Object dummy)
        {
            if (m_InitialStartup)
            {
                // This delay exists to stop mono problems where script compilation and startup would stop the sim
                // working properly for the session.
                System.Threading.Thread.Sleep(m_StartDelay);

                m_log.InfoFormat("[XEngine]: Performing initial script startup on {0}", m_Scene.Name);
            }

            object[] o;

            int scriptsStarted = 0;

            while (m_CompileQueue.Dequeue(out o))
            {
                if (DoOnRezScript(o))
                {
                    scriptsStarted++;

                    if (m_InitialStartup)
                        if (scriptsStarted % 50 == 0)
                            m_log.InfoFormat(
                                "[XEngine]: Started {0} scripts in {1}", scriptsStarted, m_Scene.Name);
                }
            }

            if (m_InitialStartup)
                m_log.InfoFormat(
                    "[XEngine]: Completed starting {0} scripts on {1}", scriptsStarted, m_Scene.Name);

            // NOTE: Despite having a lockless queue, this lock is required
            // to make sure there is never no compile thread while there
            // are still scripts to compile. This could otherwise happen
            // due to a race condition
            //
            lock (m_CompileQueue)
                m_CurrentCompile = null;

            m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
                                                                m_ScriptErrorMessage);

            m_ScriptFailCount = 0;
            m_InitialStartup = false;

            return null;
        }
        public void WaitAnyWithTimeoutSuccess()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = true;

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for(int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            int index = SmartThreadPool.WaitAny(wirs, 1500, true);

            success = (index != WaitHandle.WaitTimeout);

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
Example #58
0
		/// <summary>
		/// Wait for all work items to complete
		/// </summary>
		/// <param name="workItemResults">Array of work item result objects</param>
		/// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
		/// <param name="exitContext">
		/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. 
		/// </param>
		/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
		/// <returns>
		/// true when every work item in workItemResults has completed; otherwise false.
		/// </returns>
		internal static bool WaitAll(
			IWorkItemResult [] workItemResults,
			int millisecondsTimeout,
			bool exitContext,
			WaitHandle cancelWaitHandle)
		{
			if (0 == workItemResults.Length)
			{
				return true;
			}

			bool success;
			WaitHandle [] waitHandles = new WaitHandle[workItemResults.Length];;
			GetWaitHandles(workItemResults, waitHandles);

			if ((null == cancelWaitHandle) && (waitHandles.Length <= 64))
			{
				success = WaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
			}
			else
			{
				success = true;
				int millisecondsLeft = millisecondsTimeout;
				DateTime start = DateTime.Now;

				WaitHandle [] whs;
				if (null != cancelWaitHandle)
				{
					whs = new WaitHandle [] { null, cancelWaitHandle };
				}
				else
				{
					whs = new WaitHandle [] { null };
				}

                bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
				// Iterate over the wait handles and wait for each one to complete.
				// We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle
				// won't affect it.
				// Each iteration we update the time left for the timeout.
				for(int i = 0; i < workItemResults.Length; ++i)
				{
                    // WaitAny don't work with negative numbers
                    if (!waitInfinitely && (millisecondsLeft < 0))
                    {
                        success = false;
                        break;
                    }

					whs[0] = waitHandles[i];
					int result = WaitHandle.WaitAny(whs, millisecondsLeft, exitContext);
					if ((result > 0) || (WaitHandle.WaitTimeout == result))
					{
						success = false;
						break;
					}

					if (!waitInfinitely)
					{
                        // Update the time left to wait
						TimeSpan ts = DateTime.Now - start;
						millisecondsLeft = millisecondsTimeout - (int)ts.TotalMilliseconds;
					}
				}
			}
			// Release the wait handles
			ReleaseWaitHandles(workItemResults);

			return success;
		}
        public void WaitAllWithEmptyArray()
        {
            IWorkItemResult [] wirs = new IWorkItemResult[0];

            bool success = SmartThreadPool.WaitAll(wirs);;

            Assert.IsTrue(success);
        }
Example #60
0
        public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
        {
            if (script.StartsWith("//MRM:"))
                return;

            List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());

            List<string> names = new List<string>();
            foreach (IScriptModule m in engines)
                names.Add(m.ScriptEngineName);

            int lineEnd = script.IndexOf('\n');

            if (lineEnd > 1)
            {
                string firstline = script.Substring(0, lineEnd).Trim();

                int colon = firstline.IndexOf(':');
                if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
                {
                    string engineName = firstline.Substring(2, colon-2);

                    if (names.Contains(engineName))
                    {
                        engine = engineName;
                        script = "//" + script.Substring(script.IndexOf(':')+1);
                    }
                    else
                    {
                        if (engine == ScriptEngineName)
                        {
                            SceneObjectPart part =
                                    m_Scene.GetSceneObjectPart(
                                    localID);
                         
                            TaskInventoryItem item =
                                    part.Inventory.GetInventoryItem(itemID);

                            ScenePresence presence = 
                                    m_Scene.GetScenePresence(
                                    item.OwnerID);

                            if (presence != null)
                            {
                               presence.ControllingClient.SendAgentAlertMessage(
                                        "Selected engine unavailable. "+
                                        "Running script on "+
                                        ScriptEngineName,
                                        false);
                            }
                        }
                    }
                }
            }

            if (engine != ScriptEngineName)
                return;

            // If we've seen this exact script text before, use that reference instead
            if (m_uniqueScripts.ContainsKey(script))
                script = m_uniqueScripts[script];
            else
                m_uniqueScripts[script] = script;

            Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};

            if (stateSource == (int)StateSource.ScriptedRez)
            {
                lock (m_CompileDict)
                {
                    m_CompileDict[itemID] = 0;
                }

                DoOnRezScript(parms);
            }
            else
            {
                m_CompileQueue.Enqueue(parms);
                lock (m_CompileDict)
                {
                    m_CompileDict[itemID] = 0;
                }

                if (m_CurrentCompile == null)
                {
                    // NOTE: Although we use a lockless queue, the lock here
                    // is required. It ensures that there are never two
                    // compile threads running, which, due to a race
                    // conndition, might otherwise happen
                    //
                    lock (m_CompileQueue)
                    {
                        if (m_CurrentCompile == null)
                            m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
                    }
                }
            }
        }