Exemplo n.º 1
0
		public void Run(StopWatch stopWatch)
		{
			stopWatch.Start();

			CheckPoint point = stopWatch.Mark("Correlated Requests");
		    CheckPoint responsePoint = stopWatch.Mark("Correlated Responses");

		    var pool = new ManagedThreadPool<CorrelatedController>(DoWorker, 10, 10);
            try
            {

                for (int index = 0; index < _attempts; index++)
                {
                    var controller = new CorrelatedController(_bus, OnSuccess, OnTimeout);
                    pool.Enqueue(controller);
                }

                point.Complete(_attempts);

                _finishedEvent.WaitOne(TimeSpan.FromSeconds(60), true);

                responsePoint.Complete(_timeouts + _successes);
            }
            finally
            {
                pool.Dispose();
            }

			Console.WriteLine("Attempts: {0}, Succeeded: {1}, Timeouts: {2}", _attempts, _successes, _timeouts);

			stopWatch.Stop();
		}
Exemplo n.º 2
0
        /// <summary>
        /// 响应计数事件
        /// </summary>
        /// <param name="callArgs"></param>
        private void NotifyEventArgs(CallEventArgs callArgs)
        {
            //调用计数
            ManagedThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    var arr           = state as ArrayList;
                    var statusService = arr[0] as ServerStatusService;
                    var eventArgs     = arr[1] as CallEventArgs;

                    //调用计数服务
                    statusService.Counter(eventArgs);

                    //响应消息
                    MessageCenter.Instance.Notify(eventArgs);
                }
                catch (Exception ex)
                {
                    //TODO
                }
            }, new ArrayList {
                status, callArgs
            });
        }
Exemplo n.º 3
0
        ///<summary>
        /// 执行计划任务
        ///</summary>
        public static void Execute()
        {
            Config.Event[] simpleItems = WshelperConfigs.GetConfig().ScheduledEvents;

            List <Event> list = new List <Event>();

            foreach (Config.Event newEvent in simpleItems)
            {
                if (!newEvent.Enabled)
                {
                    continue;
                }
                Event e = new Event();
                e.Key          = newEvent.Key;
                e.ScheduleType = newEvent.ScheduleType;
                list.Add(e);
            }

            Event[] items = list.ToArray();
            Event   item  = null;

            for (int i = 0; i < items.Length; i++)
            {
                item = items[i];
                //if (item.ShouldExecute)
                //{
                //    item.UpdateTime();
                IEvent e = item.IEventInstance;
                ManagedThreadPool.QueueUserWorkItem(e.Execute);
                //}
            }
        }
Exemplo n.º 4
0
        /// <summary>Adds a new x, y data pair to continuous data set.</summary>
        /// <param name="x">New x-axis value.</param>
        /// <param name="y">New y-axis value.</param>
        public void Calculate(double x, double y)
        {
            lock (m_xValues)
            {
                // Adds latest values to regression data set.
                m_xValues.Add(x);
                m_yValues.Add(y);

                // Keeps a constant number of points by removing them from the left.
                while (m_xValues.Count > m_pointCount)
                {
                    m_xValues.RemoveAt(0);
                }

                while (m_yValues.Count > m_pointCount)
                {
                    m_yValues.RemoveAt(0);
                }
            }

            if (m_xValues.Count >= m_pointCount && !m_calculating)
            {
                // Performs curve fit calculation on seperate thread, since it could be time consuming.
#if ThreadTracking
                ManagedThread thread = ManagedThreadPool.QueueUserWorkItem(PerformCalculation);
                thread.Name = "TVA.Math.RealTimeSlope.PerformCalculation()";
#else
                ThreadPool.QueueUserWorkItem(PerformCalculation);
#endif
            }
        }
        public void Run(StopWatch stopWatch)
        {
            stopWatch.Start();

            CheckPoint point         = stopWatch.Mark("Correlated Requests");
            CheckPoint responsePoint = stopWatch.Mark("Correlated Responses");

            var pool = new ManagedThreadPool <CorrelatedController>(DoWorker, 10, 10);

            try
            {
                for (int index = 0; index < _attempts; index++)
                {
                    var controller = new CorrelatedController(_bus, OnSuccess, OnTimeout);
                    pool.Enqueue(controller);
                }

                point.Complete(_attempts);

                _finishedEvent.WaitOne(TimeSpan.FromSeconds(60), true);

                responsePoint.Complete(_timeouts + _successes);
            }
            finally
            {
                pool.Dispose();
            }

            Console.WriteLine("Attempts: {0}, Succeeded: {1}, Timeouts: {2}", _attempts, _successes, _timeouts);

            stopWatch.Stop();
        }
Exemplo n.º 6
0
        /// <summary>
        /// 对页面进行更新
        /// </summary>
        public void Update(TimeSpan timeSpan)
        {
            ManagedThreadPool.QueueUserWorkItem(state =>
            {
                TimeSpan span = (TimeSpan)state;
                Thread.Sleep(span);

                (this as IUpdateItem).Update(DateTime.MaxValue);
            }, timeSpan);
        }
        /// <summary>
        /// When a connection is made, get a network stream and start the worker thread.
        /// The worker thread uses the managed thread pool, which is safe for handling
        /// work that takes a lot of time.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnConnected(object sender, TcpServerEventArgs e)
        {
            ConnectionState cs = e.ConnectionState;
            NetworkStream   ns = new NetworkStream(cs.Connection, true);

            ns.ReadTimeout  = readTimeout;
            ns.WriteTimeout = writeTimeout;
            NetworkStreamConnection conn = new NetworkStreamConnection(ns, cs);

            ManagedThreadPool.QueueUserWorkItem(ConnectionProcess, conn);
        }
Exemplo n.º 8
0
        private bool BakExport(string sourceDir, string targetDir)
        {
            try {
                ManagedThreadPool.QueueUserWorkItem((o) => CopyDir(sourceDir, targetDir));

                return(true);
            } catch (Exception ex) {
                Message.Info(string.Format("message:{0},StackTrace:{1}", ex.Message, ex.StackTrace));
                return(false);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 执行单个任务
        /// </summary>
        /// <param name="task"></param>
        private static void ExecuteTask(TaskBase task)
        {
            //设置最后一次执行时间
            task.LastExecuteTime = DateTime.Now;
            RecordExecuteTime(task.Type, DateTime.Now);

            //Log4Helper.Info("task:" + task.TaskName + ",type:" + task.Type + ",time:" + DateTime.Now.ToString());
            ManagedThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(task.Execute));

            //  task.Execute(null);
        }
Exemplo n.º 10
0
        public override void WriteComplete()
        {
            //替换内容
            string content = ReplaceContext(pageContent.ToString());
            string path    = HttpContext.Current.Request.Url.PathAndQuery;

            //启动生成线程
            ManagedThreadPool.QueueUserWorkItem(WriteFile, new ArrayList {
                content, path
            });
        }
Exemplo n.º 11
0
        public static void Execute()
        {
            Hyt.Model.Common.Event[] simpleItems = Config.Config.Instance.GetScheduleConfig().Events;
            //Event[] items;

            if (items == null)
            {
                List <Event> list = new List <Event>();

                var allDealer = Hyt.BLL.Stores.StoresBo.Instance.GetAllStores();
                foreach (var d in allDealer)
                {
                    if (string.IsNullOrWhiteSpace(d.AppID) || string.IsNullOrWhiteSpace(d.AppSecret))
                    {
                        continue;
                    }

                    foreach (Hyt.Model.Common.Event newEvent in simpleItems)
                    {
                        if (!newEvent.Enabled)
                        {
                            continue;
                        }
                        Event e = new Event();
                        e.Key          = newEvent.Key;
                        e.Minutes      = newEvent.Minutes;
                        e.ScheduleType = newEvent.ScheduleType;
                        e.TimeOfDay    = newEvent.TimeOfDay;
                        e.DealerSysNo  = d.SysNo;
                        list.Add(e);
                    }
                }

                items = list.ToArray();
            }

            Event item = null;

            if (items != null)
            {
                for (int i = 0; i < items.Length; i++)
                {
                    item = items[i];
                    if (item.ShouldExecute)
                    {
                        item.UpdateTime();
                        IEvent e = item.IEventInstance;
                        ManagedThreadPool.QueueUserWorkItem(new WaitCallback(e.Execute), item.DealerSysNo);
                    }
                }
            }
        }
Exemplo n.º 12
0
        public static void SendPings(Post post, string pingUrls)
        {
            // Split ping urls into string array
            string[] pingUrlsArray = pingUrls.Split('\n');

            // Gather information to pass to ping service(s)
            string name    = SiteSettings.Get().Title;
            string url     = post.Category.IsUncategorized ? new Macros().FullUrl(new Urls().Home) : new Macros().FullUrl(post.Category.Url);
            string feedUrl = SiteSettings.Get().ExternalFeedUrl ?? new Macros().FullUrl(VirtualPathUtility.ToAbsolute("~/feed/"));

            XmlRpcPings pinger = new XmlRpcPings(name, url, feedUrl, pingUrlsArray);

            ManagedThreadPool.QueueUserWorkItem(new WaitCallback(pinger.SendPings));
        }
Exemplo n.º 13
0
        /// <summary>
        /// 对页面进行更新
        /// </summary>
        public void Update(TimeSpan timeSpan)
        {
            ManagedThreadPool.QueueUserWorkItem(state =>
            {
                ArrayList arr        = state as ArrayList;
                IStaticPageItem item = (IStaticPageItem)arr[0];
                TimeSpan span        = (TimeSpan)arr[1];
                Thread.Sleep(span);

                item.Update();
            }, new ArrayList {
                this, timeSpan
            });
        }
Exemplo n.º 14
0
        public static void Execute()
        {
            Discuz.Config.Event[] simpleItems = ScheduleConfigs.GetConfig().Events;
            Event[] items;
#if NET1
            ArrayList list = new ArrayList();
#else
            List <Event> list = new List <Event>();
#endif

            foreach (Discuz.Config.Event newEvent in simpleItems)
            {
                if (!newEvent.Enabled)
                {
                    continue;
                }
                Event e = new Event();
                e.Key          = newEvent.Key;
                e.Minutes      = newEvent.Minutes;
                e.ScheduleType = newEvent.ScheduleType;
                e.TimeOfDay    = newEvent.TimeOfDay;

                list.Add(e);
            }


#if NET1
            items = (Event[])list.ToArray(typeof(Event));
#else
            items = list.ToArray();
#endif

            Event item = null;

            if (items != null)
            {
                for (int i = 0; i < items.Length; i++)
                {
                    item = items[i];
                    if (item.ShouldExecute)
                    {
                        item.UpdateTime();
                        IEvent e = item.IEventInstance;
                        ManagedThreadPool.QueueUserWorkItem(new WaitCallback(e.Execute));
                    }
                }
            }
        }
 /// <summary>
 /// 输出错误
 /// </summary>
 /// <param name="error"></param>
 public void Write(Exception error)
 {
     ManagedThreadPool.QueueUserWorkItem(state =>
     {
         try
         {
             if (OnError != null)
             {
                 OnError(state as Exception);
             }
         }
         catch (Exception)
         {
         }
     }, error);
 }
Exemplo n.º 16
0
        public void Run(StopWatch watch)
        {
            _container = new HeavyLoadContainer();

            _bus = _container.Resolve <IServiceBus>();

            var management = MsmqEndpointManagement.New(_bus.Endpoint.Address.Uri);

            management.Purge();

            watch.Start();

            //BatchServiceComponent component = new BatchServiceComponent();

            //_bus.Subscribe(component);

            _container.AddComponent <BatchServiceComponent>();

            _bus.Subscribe <BatchServiceComponent>();

            int batchCount = 100;

            CheckPoint publishCheckpoint = watch.Mark("Publishing " + batchCount + " batches");

            _threads = new ManagedThreadPool <int>(delegate(int batchLength) { SendBatch(batchLength); }, 10, 10);

            for (int i = 0; i < batchCount; i++)
            {
                _threads.Enqueue(100);
            }

            for (int i = 0; i < batchCount; i++)
            {
                bool received = BatchServiceComponent.Received.WaitOne(TimeSpan.FromSeconds(30), true);
                if (!received)
                {
                    _log.Error("Something went wrong, we never got a batch completed");
                    break;
                }
            }

            publishCheckpoint.Complete(batchCount * 100);

            watch.Stop();

            _log.Info("Test Complete");
        }
 /// <summary>
 /// 输出日志
 /// </summary>
 /// <param name="log"></param>
 /// <param name="type"></param>
 public void Write(string log, LogType type)
 {
     ManagedThreadPool.QueueUserWorkItem(state =>
     {
         try
         {
             var arr = state as ArrayList;
             if (OnLog != null)
             {
                 OnLog(arr[0] as string, (LogType)arr[1]);
             }
         }
         catch (Exception)
         {
         }
     }, new ArrayList {
         log, type
     });
 }
        public MemoryDataProvider([NotNull] string filename, [NotNull] string serializationPath)
        {
            Assert.ArgumentNotNullOrEmpty(serializationPath, nameof(serializationPath));
            Assert.ArgumentNotNullOrEmpty(filename, nameof(filename));

            ID = GetId(filename);
            Log.Debug("MemoryDataProvider " + ID + " is starting", this);
            filename          = MainUtil.MapPath(filename);
            serializationPath = Path.GetFullPath(Path.Combine(MainUtil.MapPath("/"), serializationPath));

            var started = new AutoResetEvent(false);

            ManagedThreadPool.QueueUserWorkItem(
                a =>
            {
                lock (this)
                {
                    started.Set();
                    try
                    {
                        using (new SecurityDisabler())
                        {
                            lock (string.Intern(filename))
                            {
                                if (!LoadFromFile(filename))
                                {
                                    LoadTree(serializationPath);
                                    SaveToFile(filename);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(e.ToString(), this);
                    }
                }
            });

            started.WaitOne();
        }
Exemplo n.º 19
0
        protected void gvSchedule_SelectedIndexChanged(object sender, EventArgs e)
        {
            ILog log     = new AppLog();
            var  logInfo = new LogInfo
            {
                MethodInstance = MethodBase.GetCurrentMethod(),
                ThreadInstance = Thread.CurrentThread
            };

            try
            {
                if (gvSchedule.SelectedIndex != -1)
                {
                    var dataKey = gvSchedule.DataKeys[gvSchedule.SelectedIndex];
                    if (dataKey != null)
                    {
                        var key = dataKey.Value.ToString();

                        var s = Schedule.Single(key);

                        var instance = s.IScheduleInstance;
                        ManagedThreadPool.QueueUserWorkItem(instance.Execute);

                        s.LastCompletedTime = DateTime.Now;
                        s.Update();

                        log.Info($"ISchedule Manually: {s.ScheduleType}", logInfo);
                    }

                    //this.ClientScript.RegisterClientScriptBlock(typeof(string), "success", string.Format("任务:{0}执行成功');", s.ScheduleType), true);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex, logInfo);

                //this.ClientScript.RegisterClientScriptBlock(typeof(string), "failed", string.Format("alert('{0}');", ex.Message.ToString()), true);
            }
        }
Exemplo n.º 20
0
        void DoPushWork(object state)
        {
            while (true)
            {
                //启用线程来进行处理
                ManagedThreadPool.QueueUserWorkItem(obj =>
                {
                    //响应定时信息
                    if (statuslist.Count > 0)
                    {
                        try
                        {
                            var status = GetServerStatus();
                            MessageCenter.Instance.Notify(status);
                        }
                        catch (Exception ex)
                        {
                            //TODO
                        }
                    }
                });

                //每分钟进行一次计数
                if (counterlist.Count >= 60)
                {
                    counterlist.Reset();
                }
                else
                {
                    counterlist.Count++;
                }

                //每秒推送一次
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// 启动静态管理类
        /// </summary>
        /// <param name="interval">检测间隔时间:单位(秒)</param>
        public static void Start(int interval, bool isStartUpdate)
        {
            if (isRunning)
            {
                return;
            }

            isRunning = true;

            if (isStartUpdate)
            {
                //启动一个临时线程生成
                ManagedThreadPool.QueueUserWorkItem(state => RunUpdate(DateTime.MaxValue));
            }

            //启动一个循环线程生成
            Thread thread = new Thread(state =>
            {
                if (state == null)
                {
                    return;
                }

                var timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(state));
                while (true)
                {
                    RunUpdate(DateTime.Now);

                    //休眠间隔
                    Thread.Sleep(timeSpan);
                }
            });

            //单位:秒
            thread.Start(interval);
        }
Exemplo n.º 22
0
 /// <summary>
 /// 执行统计操作
 /// </summary>
 public void Enqueue()
 {
     ManagedThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Process));
 }
Exemplo n.º 23
0
        internal void Listener_ThreadStart(CancellationToken ctToken)
        {
            try
            {
                _managedThreadPool   = new ManagedThreadPool(_maxWorkerThreads);
                _listenerEndedSignal = new ManualResetEvent(false);
                _listenerCtSource    = CancellationTokenSource.CreateLinkedTokenSource(ctToken);

                //_listenerCtSource.Token.Register(() => { /* for debugging purposes. */ });

                _callbackThread = new Thread(Callback_ThreadStart);
                _callbackThread.IsBackground = false;
                _callbackThread.Start();

                _tasksExecutedCount = 0;

                _listenerStartedSignal.Set();

                while (!_listenerCtSource.IsCancellationRequested)
                {
                    try
                    {
                        CleanupAndRescheduleTasks();

                        var taskInfos = ProcessPendingTasks(_managedThreadPool.MaxThreads);

                        while (ManageTasksLifeTime(taskInfos) > 0)
                        {
                            //Allows other threads to execute
                            Thread.Sleep(1);
                        }

                        //Only counts tasks that acquired lock
                        _tasksExecutedCount += taskInfos.Where(t => t.RealTaskInvokedFlag).Count();

                        //Release all task locks
                        foreach (var taskInfo in taskInfos)
                        {
                            _taskManager.LockManager.Release(taskInfo.LockInfo);
                            taskInfo.Dispose();
                        }

                        ResumeCallbackThread();
                    }
                    catch (ThreadAbortException ex)
                    {
                        //Ignores thread abort exceptions and quits
                        break;
                    }
                    catch (Exception ex)
                    {
                        LatestListenerException = ex;
                        ex.LogException();
                    }

                    //Sleeps regardless if the previous block threw an exception or not.
                    Thread.Sleep(_mainLoopWaitTime);
                }
            }
            catch (ThreadAbortException ex)
            {
                //Ignores thread abort exceptions
            }
            catch (Exception ex)
            {
                LatestListenerException = ex;
                ex.LogException();
            }
            finally
            {
                _listenerStartedSignal = null;

                var pool = _managedThreadPool;
                if (pool != null)
                {
                    _managedThreadPool = null;
                    pool.StopPool(waitTillStops: true);
                }

                var endSignal = _listenerEndedSignal;

                if (endSignal != null)
                {
                    _listenerEndedSignal = null;
                    endSignal.Set();
                }
            }
        }
Exemplo n.º 24
0
        public static void CheckPost(Post post)
        {
            LinkParser lp = new LinkParser(SiteSettings.Get().Title, post.Title, new Macros().FullUrl(post.Url), post.Body, post.Excerpt("", "", "", 300), SiteSettings.BaseUrl);

            ManagedThreadPool.QueueUserWorkItem(new WaitCallback(lp.CheckPost));
        }
Exemplo n.º 25
0
 public MyWaitCallback(ManagedThreadPool.WaitingCallback wc)
 {
     Waiting = wc;
 }