public ActionResult vrlist()
        {
            List <string> list      = null;
            List <string> sortList  = null;
            long          count     = 0;
            long          sortcount = 0;

            using (ServiceStack.Redis.IRedisClient cl = Common.Common.RedisPool.GetClient())
            {
                count = cl.GetListCount(Common.ConfigSettings.RedisListKey);

                list = cl.GetRangeFromList(Common.ConfigSettings.RedisListKey, count > 100 ? (int)(count - 100) : 0, (int)count - 1);

                sortList = cl.GetRangeFromSortedSetDesc(Common.ConfigSettings.RedisSortListKey, 1, 10);

                sortcount = cl.GetSortedSetCount(Common.ConfigSettings.RedisSortListKey);
            }
            ViewBag.list      = string.Join(",", list.ToArray());
            ViewBag.count     = count.ToString();
            ViewBag.qcount    = Common.Common.GetQueueCount().ToString();
            ViewBag.sortlist  = string.Join(",", sortList.ToArray());
            ViewBag.sortcount = sortcount;

            int maxthreadcount = 0;
            //int currthreadcount = 0;
            int availthreadcount = 0;
            int iocouint         = 0;

            ThreadPool.GetMaxThreads(out maxthreadcount, out iocouint);
            ThreadPool.GetAvailableThreads(out availthreadcount, out iocouint);

            ViewBag.maxthreadcount = maxthreadcount;

            ViewBag.availthreadcount = availthreadcount;



            return(View());
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var availableWorkingThreadCount = 0;
                var availableAsyncIoThreadCount = 0;
                ThreadPool.GetAvailableThreads(out availableWorkingThreadCount, out availableAsyncIoThreadCount);
                AddErrors(new IdentityResult(string.Format("[IIS Host] Thread Id {0}, ThreadPool Thread: {1}",
                                                           Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread)));
                AddErrors(new IdentityResult(string.Format("[IIS Host] current working thread: {0}, current async thread: {1}", availableWorkingThreadCount, availableAsyncIoThreadCount)));

                HttpClient httpClient = new HttpClient();
                var        response   = httpClient.GetStringAsync("https://msdn.microsoft.com/en-us/library/system.threading.thread.isthreadpoolthread(v=vs.110).aspx");
                await      response;

                AddErrors(new IdentityResult(string.Format("[IIS Host] Thread Id {0}, ThreadPool Thread: {1}",
                                                           Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread)));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var sw       = Stopwatch.StartNew();
            var response = await base.SendAsync(request, cancellationToken);

            sw.Stop();

            if (_contentTypeLst.Contains(response.Content.Headers.ContentType.MediaType))
            {
                int wt, cpt = 0;
                ThreadPool.GetAvailableThreads(out wt, out cpt);
                var log = String.Format("[{0}] [{1}] 访问 [{2}] 耗时 [{3}]  线程池剩余[{4},{5}] {6}", request.Method, GetClientIP(request), request.RequestUri, sw.ElapsedMilliseconds, wt, cpt, Environment.NewLine);
                if (_isLogResult)
                {
                    log += GetResult(response);
                }
                log += Environment.NewLine;
                _logger.Info(log);
            }

            return(response);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            int countThread;
            int completionPortThreads;

            ThreadPool.GetAvailableThreads(out countThread, out completionPortThreads);
            Console.WriteLine($"The number of available worker threads - {countThread}, number of available asynchronous I/O threads {completionPortThreads}");

            ThreadPool.GetMaxThreads(out countThread, out completionPortThreads);
            Console.WriteLine($"The number of MAX worker threads - {countThread}, number of MAX asynchronous I/O threads {completionPortThreads}");

            ThreadPool.GetMinThreads(out countThread, out completionPortThreads);
            Console.WriteLine($"The number of MIN worker threads - {countThread}, number of MIN asynchronous I/O threads {completionPortThreads}");

            ThreadPool.UnsafeQueueUserWorkItem(MethodForThread, "001");
            ThreadPool.UnsafeQueueUserWorkItem(MethodForThread, "002");
            ThreadPool.UnsafeQueueUserWorkItem(MethodForThread, "003");

            ThreadPool.GetAvailableThreads(out countThread, out completionPortThreads);
            Console.WriteLine($"The number of available worker threads - {countThread}, number of available asynchronous I/O threads {completionPortThreads}");
            Console.ReadLine();
        }
Ejemplo n.º 5
0
        public async Task <bool> Start(Uri urlToCrawl)
        {
            IsCrawling = true;
            await FillScheduler();

            var tasks = new List <Task>();

            ThreadPool.GetAvailableThreads(out _threadsAvailable, out _);

            while (IsCrawling && _threadsAvailable > _threadLimit)
            {
                for (var i = _threadLimit; i > 0; i--)
                {
                    Uri crawl = urlToCrawl;
                    tasks.Add(Task.Run(() => StartCrawlerAsync(crawl, new Link())));
                    _threadLimit--;
                    if (_scheduler.HasNext())
                    {
                        urlToCrawl = StringToUri(_scheduler.GetNext().Address);
                    }
                }
            }

            //Single-threaded crawler
            //while (true)
            //{
            //    Uri crawl = urlToCrawl;
            //    //tasks.Add(Task.Run(() => StartCrawlerAsync(crawl, new Link())));
            //    await StartCrawlerAsync(crawl, new Link());
            //    _threadLimit--;
            //    if (_scheduler.HasNext())
            //    {
            //        urlToCrawl = StringToUri(_scheduler.GetNext().Address);
            //    }
            //}
            await Task.WhenAll(tasks);

            return(false);
        }
Ejemplo n.º 6
0
 private void simpleButton4_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show(this, "此功能耗时较长,确定要开始执行删除吗?", "询问", MessageBoxButtons.YesNo) == DialogResult.Yes)
     {
         ThreadPool.SetMinThreads(5, 5);   //设置最小线程数为5个
         ThreadPool.SetMaxThreads(20, 20); //设置最大线程数为20个,这两个方法要配合使用才能控制线程数量
         if (gridView1.DataSource != null)
         {
             DataTable      dt = ((DataView)gridView1.DataSource).ToTable();
             AutoResetEvent mainAutoResetEvent = new AutoResetEvent(false);
             foreach (DataRow dr in dt.Rows)
             {
                 ThreadPool.QueueUserWorkItem(muiltiDeleteNoHttp, dr);
             }
             RegisteredWaitHandle registeredWaitHandle = null;
             registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), new WaitOrTimerCallback(delegate(object obj, bool timeout)
             {
                 int workerThreads  = 0;
                 int maxWordThreads = 0;
                 int compleThreads  = 0;
                 ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
                 ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
                 //Console.WriteLine("线程检测===========可用线程{0},最大线程{1}", workerThreads, maxWordThreads);
                 //当可用的线数与池程池最大的线程相等时表示线程池中所有的线程已经完成
                 if (workerThreads == maxWordThreads)
                 {
                     mainAutoResetEvent.Set();
                     registeredWaitHandle.Unregister(null);
                 }
             }), null, 1000, false);
             mainAutoResetEvent.WaitOne();
             MessageBox.Show("程序执行完毕!");
         }
         else
         {
             MessageBox.Show("请先登录网站!");
         }
     }
 }
Ejemplo n.º 7
0
        public string GetThreadPool()
        {
            string result = "";
            int    workerThreadsAvailable;
            int    completionPortThreadsAvailable;
            int    workerThreadsMax;
            int    completionPortThreadsMax;
            int    workerThreadsMin;
            int    completionPortThreadsMin;

            ThreadPool.GetAvailableThreads(out workerThreadsAvailable, out completionPortThreadsAvailable);
            ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax);
            ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin);

            DateTime Complete = DateTime.Now;

            result = " " + $"AW:{workerThreadsAvailable} AC:{completionPortThreadsAvailable}" +
                     $" MaxW:{workerThreadsMax} MaxC:{completionPortThreadsMax}" +
                     $" MinW:{workerThreadsMin} MinC:{completionPortThreadsMin} ";

            return(result);
        }
Ejemplo n.º 8
0
        public async Task <string> AddAsync(int value1, int value2, int delay)
        {
            DateTime Begin = DateTime.Now;
            int      workerThreadsAvailable;
            int      completionPortThreadsAvailable;
            int      workerThreadsMax;
            int      completionPortThreadsMax;
            int      workerThreadsMin;
            int      completionPortThreadsMin;

            ThreadPool.GetAvailableThreads(out workerThreadsAvailable, out completionPortThreadsAvailable);
            ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax);
            ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin);
            await Task.Delay(delay);

            var      fooUrl   = Url.Action("ResponAndAwait2");
            DateTime Complete = DateTime.Now;

            return($"AW:{workerThreadsAvailable} AC:{completionPortThreadsAvailable}" +
                   $" MaxW:{workerThreadsMax} MaxC:{completionPortThreadsMax}" +
                   $" MinW:{workerThreadsMin} MinC:{completionPortThreadsMin} ({Begin.TimeOfDay} - {Complete.TimeOfDay})");
        }
Ejemplo n.º 9
0
        private void CheckThreadPool(object state, bool timeout)
        {
            Object locker = new Object();

            lock (locker)
            {
                int maxWorkerThreads, workerThreads;
                int portThreads;
                ThreadPool.GetMaxThreads(out maxWorkerThreads, out portThreads);
                ThreadPool.GetAvailableThreads(out workerThreads, out portThreads);
                if (maxWorkerThreads - workerThreads == 0)
                {
                    // 走到这里,所有线程都结束了
                    rhw.Unregister(null);
                    DateTime end = DateTime.Now;
                    StringHelp.Write(StringHelp.pathError, end.ToString() + "执行结束。" + "用时:" + DateHelp.DateDiff(end, dt) + "获取个数:" + num + "\r\n");
                    label3.Text = end.ToString() + "执行完毕,已将检索结果导出到与导入文件所在的相同目录。";
                    MessageBox.Show(end.ToString() + "执行结束。" + "用时:" + DateHelp.DateDiff(end, dt) + "。" +
                                    "\r\n获取个数:" + num + ", 已将检索结果导出到与导入文件所在的相同目录。\r\n");
                }
            }
        }
Ejemplo n.º 10
0
        private void SockListen(object obj)
        {
            SocketModule s_i = (SocketModule)obj;
            int          a   = s_i.l_S.Count;

            if (a == 0)
            {
                return;
            }
            int bufnum = cache_num / module_l + 1;//单位为(module_l(b)大小)

            s_i.l_S[a - 1].buf      = new byte[bufnum * module_l];
            s_i.l_S[a - 1].I_BufNum = bufnum;
            WaitCallback wcb = new WaitCallback(p => ThreadFun_Download_File(s_i.l_S[s_i.l_S.Count - 1], s_i));
            int          workerThreads, availabeThreads;

            ThreadPool.GetAvailableThreads(out workerThreads, out availabeThreads);
            if (workerThreads > 0)//可用线程数>0
            {
                ThreadPool.QueueUserWorkItem(wcb);
            }
        }
Ejemplo n.º 11
0
        static void LogRunningTime(Action callback)
        {
            var awailableWorkingThreadCount = 0;
            var awailableAsyncIoThreadCount = 0;

            var watch = Stopwatch.StartNew();

            watch.Start();

            callback();

            while (maxWorkerThreads != awailableWorkingThreadCount)
            {
                Thread.Sleep(500);
                ThreadPool.GetAvailableThreads(out awailableWorkingThreadCount, out awailableAsyncIoThreadCount);

                Console.WriteLine("[Alive] working thread: {0}, async IO thread: {1}", awailableWorkingThreadCount, awailableAsyncIoThreadCount);
            }

            watch.Stop();
            Console.WriteLine("[Finsih] current awailible working thread is {0} and used {1}ms", awailableWorkingThreadCount, watch.ElapsedMilliseconds);
        }
Ejemplo n.º 12
0
        static void Main1()
        {
            //ThreadPool.QueueUserWorkItem(new WaitCallback(PoolFunc1), "aaa");
            ThreadPool.QueueUserWorkItem(PoolFunc1, "aaa");
            ThreadPool.QueueUserWorkItem(new WaitCallback(PoolFunc2));


            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Main Thread " + i.ToString());
            }
            int workerthreads, iothreads;

            ThreadPool.GetAvailableThreads(out workerthreads, out iothreads);
            //ThreadPool.SetMinThreads
            //ThreadPool.SetMaxThreads
            //ThreadPool.GetMinThreads
            Console.WriteLine(workerthreads);
            Console.WriteLine(iothreads);

            Console.ReadLine();
        }
Ejemplo n.º 13
0
 private void InitConnection()
 {
     if (pullValue.Count > 0)
     {
         ThreadPool.GetAvailableThreads(out workerThread, out asyncWorkerThread);
         string value;
         while (workerThread == 0)
         {
             Thread.Sleep(1000);
             ThreadPool.GetAvailableThreads(out workerThread, out asyncWorkerThread);
         }
         lock (pullValue)
         {
             value = pullValue.Dequeue();
         }
         var sqlConnection = new SqlConnection(connectionString);
         var command       = sqlConnection.CreateCommand();
         command.CommandText = commandText;
         command.Parameters.Add(new SqlParameter("@StoreId", value));
         this.operateAsyncCommand(command);
     }
 }
Ejemplo n.º 14
0
        private void LookThreadPoolSize()
        {
            int workerThreadsMin         = 0;
            int completionPortThreadsMin = 0;

            ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin);

            int workerThreadsMax         = 0;
            int completionPortThreadsMax = 0;

            ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax);

            int workerThreads         = 0;
            int completionPortThreads = 0;

            ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);

            SetTip(String.Format("线程池:{0}({1}-{2}) - {3}({4}-{5})  工作线程数:{6}",
                                 workerThreads, workerThreadsMin, workerThreadsMax,
                                 completionPortThreads, completionPortThreadsMin, completionPortThreadsMax,
                                 workerThreadsMax - workerThreads));
        }
Ejemplo n.º 15
0
        private void OnPingCommandReceived(object sender, EventArgs e)
        {
            if ((_status == WorkerStatus.Running) != _component.IsRunning)
            {
                _waitForExit.Set();
                return;
            }

            int tcWK;
            int tcIO;

            ThreadPool.GetAvailableThreads(out tcWK, out tcIO);

            if (tcWK == 0 || tcIO < 500)
            {
                Log(string.Format("thread count overflow! \r\nWorkerThread={0}, IOThread={1} : remain", tcWK, tcIO));//, EventLogEntryType.Warning, 1609);
            }

            ThreadPool.QueueUserWorkItem(delegate(object state) {
                _console.PingResponse();
            });
        }
Ejemplo n.º 16
0
        public void GetAvailableThreads()
        {
            int cpuCount = Environment.ProcessorCount;

            if (cpuCount > 16)
            {
                Assert.Inconclusive("This test doesn't work well with a high number of processor cores.");
            }

            ManualResetEvent mre = new ManualResetEvent(false);
            var sw = Stopwatch.StartNew();
            int i, workerThreads, completionPortThreads;

            try {
                Assert.IsTrue(ThreadPool.SetMaxThreads(cpuCount, cpuCount));

                while (true)
                {
                    ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
                    if (workerThreads == 0)
                    {
                        break;
                    }

                    if (sw.Elapsed.TotalSeconds >= 30)
                    {
                          {
                            Console.WriteLine("workerThreads = {0}, completionPortThreads = {1}", workerThreads, completionPortThreads);
                            Assert.Fail("did not reach 0 available threads");
                        }
                    }

                    ThreadPool.QueueUserWorkItem(GetAvailableThreads_Callback, mre);
                    Thread.Sleep(1);
                }
            } finally {
                mre.Set();
            }
        }
	public static void Main(){
		int workerThreads = 0;
		int completionPortThreads = 0;
		ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
		Console.WriteLine("Minimum number of worker threads in thread pool: {0} ", 
											workerThreads);
		Console.WriteLine("Minimum number of completion port threads in thread pool: {0} ", 
											completionPortThreads);
		ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
		Console.WriteLine("Available worker threads in thread pool: {0} ", workerThreads);
		Console.WriteLine("Available completion port threads in thread pool: {0} ", 
											completionPortThreads);

		for(int i = 0; i<45; i++){
			ThreadPool.QueueUserWorkItem(new WaitCallback(Run), i);
			Thread.Sleep(1000); // sleep twice as long as it takes to start a threadpool thread
			ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
			Console.Write("\nAvailable worker threads in thread pool: {0} ", workerThreads);
			Console.WriteLine("\nAvailable completion port threads in thread pool: {0}", 
												completionPortThreads);
		}
	} // end Main() method
Ejemplo n.º 18
0
        static internal void DebugDisplayInfo()
        {
#if !ALL_SYNC
            // Thread pool info
            int workerThreads = -1, completionPortThreads = -1;

#if !SILVERLIGHT
            // Its not possible to get this information in Silverlight. Go figure.

            ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
            Debug.WriteLine("ThreadPool Info - Available threads - Worker: {0} Completion Port: {1}", workerThreads, completionPortThreads);
#endif // !SILVERLIGHT

            workerThreads = completionPortThreads = -1;
            ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
            Debug.WriteLine("ThreadPool Info - Min threads - Worker: {0} Completion Port: {1}", workerThreads, completionPortThreads);

            workerThreads = completionPortThreads = -1;
            ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
            Debug.WriteLine("ThreadPool Info - Max threads - Worker: {0} Completion Port: {1}", workerThreads, completionPortThreads);
#endif // !ALL_SYNC
        }
Ejemplo n.º 19
0
        // method called to pick up more work
        private void WorkItemCallback(Object state)
        {
            Interlocked.Decrement(ref _workItemCount);

            // too late for more work if draining
            if (_draining)
            {
                return;
            }

            // is queue empty?
            if (_count == 0)
            {
                return;
            }

            int workerThreads, ioThreads;

            ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads);

            bool bHandledRequest = false;

            // service another request if enough worker threads are available
            if (workerThreads >= _minLocalFreeThreads)
            {
                // pick up request from the queue
                SocketHandler sh = DequeueRequest(workerThreads < _minExternFreeThreads);
                if (sh != null)
                {
                    sh.ProcessRequestNow();
                    bHandledRequest = true;
                }
            }

            if (!bHandledRequest)
            {
                ScheduleMoreWorkIfNeeded();
            }
        }
Ejemplo n.º 20
0
        private static async void Start()
        {
            int workerThreads;
            int completionPortThreads;

            ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);

            Console.WriteLine("Worker threads: {0}", workerThreads);
            Console.WriteLine("OSVersion: {0}", Environment.OSVersion);
            Console.WriteLine("ProcessorCount: {0}", Environment.ProcessorCount);
            Console.WriteLine("ClockSpeed: {0} MHZ", CpuSpeed());

            Console.WriteLine("");
            Console.WriteLine("Throughput Setting, Messages/sec");

            foreach (var t in GetThroughputSettings())
            {
                await Benchmark(t);
            }
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("Done..");
        }
Ejemplo n.º 21
0
        public void AddTask(HttpListenerContext context)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolWorkerCallback), context);

            DateTime currentDateTime = DateTime.Now;

            if (currentDateTime.Subtract(TimerForMessagesLastHour).Hours >= 1)
            {
                TimerForMessagesLastHour = currentDateTime;
                this.MainWindowViewModel.MessagesLastHour = 0;
            }
            else
            {
                this.MainWindowViewModel.MessagesLastHour++;
            }

            int availableWorkerThreads, availableCompletionPortThreads;

            ThreadPool.GetAvailableThreads(out availableWorkerThreads, out availableCompletionPortThreads);
            this.AvailableWorkerThreads         = availableWorkerThreads;
            this.AvailableCompletionPortThreads = availableCompletionPortThreads;
        }
Ejemplo n.º 22
0
        static void PoolFunc(object state)
        {
            int workerThreads, completionPortThreads;

            ThreadPool.GetAvailableThreads(out workerThreads,

                                           out completionPortThreads);

            Console.Write("WorkerThreads: {0}, CompletionPortThreads: {1}",

                          workerThreads, completionPortThreads);
            ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
            Console.WriteLine("MaxWorkerThreads: {0}, CompletionPortThreads: {1}",

                              workerThreads, completionPortThreads);

            Thread.Sleep(5000);



            string url = "http://www.baidu.com";



            HttpWebRequest myHttpWebRequest;

            HttpWebResponse myHttpWebResponse = null;

            // Creates an HttpWebRequest for the specified URL.

            myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            // Sends the HttpWebRequest, and waits for a response.

            myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

            myHttpWebResponse.Close();
        }
Ejemplo n.º 23
0
        private void button6_Click(object sender, EventArgs e)
        {
            int          czasPoczatkowy = Environment.TickCount;
            WaitCallback wc             = threadPoolMethod;

            //Sets the number of requests to the thread pool that can be active concurrently.
            //All requests above that number remain queued until thread pool threads become available.
            ThreadPool.SetMaxThreads(30, 100);

            for (int i = 0; i < 100; ++i)
            {
                ThreadPool.QueueUserWorkItem(wc, i);
            }

            //czekanie na zakończenie wątków

            int ileDostepnychWatkowWPuli  = 0; //nieużywane wątki puli
            int ileWszystkichWatkowWPuli  = 0; //wszystkie wątki puli
            int ileDzialajacychWatkowPuli = 0; //używane wątki puli
            int tmp = 0;

            do
            {
                ThreadPool.GetAvailableThreads(out ileDostepnychWatkowWPuli, out tmp);
                ThreadPool.GetMaxThreads(out ileWszystkichWatkowWPuli, out tmp);
                ileDzialajacychWatkowPuli = ileWszystkichWatkowWPuli - ileDostepnychWatkowWPuli;
                Debug.WriteLine("Ilość aktywnych wątków puli: {0}", ileDzialajacychWatkowPuli);
                Thread.Sleep(1000);
            }while (ileDzialajacychWatkowPuli > 0);

            pi /= ileWatkow;
            Debug.WriteLine("Wszystkie wątki zakończyły działanie.\nUśrednione Pi={0},błąd ={1}", pi, Math.Abs(Math.PI - pi));

            int czasKoncowy = Environment.TickCount;
            int roznica     = czasKoncowy - czasPoczatkowy;

            Console.WriteLine("Czas obliczeń: " + (roznica).ToString());
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            DateTime tempDateTime = DateTime.Now;

            Console.WriteLine("Started {0}", DateTime.Now.ToString());
            QueueItems queueItems = new QueueItems();
            QueueItem  toDoItem;

            ThreadPool.SetMinThreads(1, 0);
            ThreadPool.SetMaxThreads(10, 0);
            while (queueItems.processItems.TryDequeue(out toDoItem))
            {
                if ((toDoItem.Level == 0) || (QueueItems.IsLevelDone(toDoItem.Level - 1)))
                {
                    ThreadPool.QueueUserWorkItem(
                        new WaitCallback(ProcessItem),
                        toDoItem);
                }
                else
                {
                    queueItems.processItems.Enqueue(toDoItem);
                }
            }

            int avaiableThreads = 0;
            int comThreads      = 0;

            do
            {
                Thread.Sleep(1000);
                ThreadPool.GetAvailableThreads(out avaiableThreads, out comThreads);
            }while (avaiableThreads != 10);


            Console.WriteLine("Done {0}", DateTime.Now.ToString());
            Console.WriteLine("Total Time: {0}", DateTime.Now.Subtract(tempDateTime));
            Console.Read();
        }
Ejemplo n.º 25
0
        void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            int        iMaxWorkThreads, iMinWorkThreads, iWorkThreads, iPortThreads;
            IPEndPoint ipEnd    = new IPEndPoint(IPAddress.Any, iPort);
            Socket     mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            mySocket.Bind(ipEnd);
            mySocket.Listen(MAXCONNECT);//最大连接数
            WriteLog("Begin to listen[" + iPort.ToString() + "][" + MAXCONNECT + "]......");
            if (!NCDC.getConfigInfo())
            {
                WriteLog("getConfigInfo错误!!!");
                return;
            }

            ThreadPool.SetMinThreads(5, 5);
            ThreadPool.GetMaxThreads(out iMaxWorkThreads, out iPortThreads);
            ThreadPool.GetMinThreads(out iMinWorkThreads, out iPortThreads);
            WriteLog("线程池最大线程[" + iMaxWorkThreads.ToString() + "]最小线程[" + iMinWorkThreads.ToString() + "]");

            while (true)
            {
                try
                {
                    Socket s = mySocket.Accept();
                    clientsocket = s;
                    IPEndPoint ipEndClient = (IPEndPoint)clientsocket.RemoteEndPoint;
                    ThreadPool.GetAvailableThreads(out iWorkThreads, out iPortThreads);
                    WriteLog("线程池中新增新线程[" + ipEndClient.Address + "]当前可用线程数[" + iWorkThreads.ToString() + "]......");
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceClient), s);
                }
                catch (Exception err)
                {
                    WriteLog("守护进程异常退出!!!");
                    WriteLog(err.Message);
                }
            }
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Errors/AccessDenied", new { Area = "Identity" }));
            }

            int threads, ports, maxthreads, maxports, minthreads, minports;
            int processcount = Environment.ProcessorCount;

            ThreadPool.GetMinThreads(out minthreads, out minports);
            ThreadPool.GetMaxThreads(out maxthreads, out maxports);
            ThreadPool.GetAvailableThreads(out threads, out ports);

            Threads = threads;
            Ports   = ports;

            MaxThreads = maxthreads;
            MaxPorts   = maxports;

            MinThreads = minthreads;
            MinPorts   = minports;

            TotalProcesses = processcount;

            var     proc = Process.GetCurrentProcess();
            decimal mem  = (int)proc.WorkingSet64;

            RAM = (int)Math.Floor(mem);
            CPU = await GetCpuUsageForProcess();


            //ViewData["Labels"] = labels;
            //ViewData["Data"] = labels;
            return(Page());
        }
Ejemplo n.º 27
0
        public void StartServer()
        {
            try
            {
                var port         = 8080;
                var totalThreads = 0;

                tcpListener = new TcpListener(IPAddress.Any, port);
                tcpListener.Start();

                while (runServer)
                {
                    tcpClient = tcpListener.AcceptTcpClient();

                    /*
                     * Spawn a new thread from the thread pool for each new TCP connection. Default thread pool size
                     * is 1024 I think
                     */
                    ThreadPool.QueueUserWorkItem(AcceptTcpClient, tcpClient);

                    int maxThreads;
                    int availableThreads;
                    // Apparently there's no way to discard an out variable you don't want
                    int dontCare;

                    ThreadPool.GetMaxThreads(out maxThreads, out dontCare);
                    ThreadPool.GetAvailableThreads(out availableThreads, out dontCare);

                    totalThreads += 1;
                    DoConsoleTextUpdate("Threads available in pool: + " + availableThreads + " out of " + maxThreads
                                        + " total\r\nThreads created so far: " + totalThreads);
                }
            }
            catch (Exception e)
            {
                DoConsoleTextUpdate("Error starting server: " + e.Message);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        ///     Get a report about the registered threads in this server.
        /// </summary>
        public string GetThreadsReport()
        {
            StringBuilder sb = new StringBuilder();

            ProcessThreadCollection threads = GetThreads();

            if (threads == null)
            {
                sb.Append("OpenSim thread tracking is only enabled in DEBUG mode.");
            }
            else
            {
                sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine);
                foreach (ProcessThread t in threads)
                {
                    sb.Append("ID: " + t.Id + ", TotalProcessorTime: " + t.TotalProcessorTime + ", TimeRunning: " +
                              (DateTime.Now - t.StartTime) + ", Pri: " + t.CurrentPriority + ", State: " + t.ThreadState);
                    if (t.ThreadState == ThreadState.Wait)
                    {
                        sb.Append(", Reason: " + t.WaitReason + Environment.NewLine);
                    }
                    else
                    {
                        sb.Append(Environment.NewLine);
                    }
                }
            }
            int workers = 0, ports = 0, maxWorkers = 0, maxPorts = 0;

            ThreadPool.GetAvailableThreads(out workers, out ports);
            ThreadPool.GetMaxThreads(out maxWorkers, out maxPorts);

            sb.Append(Environment.NewLine + "*** ThreadPool threads ***" + Environment.NewLine);
            sb.Append("workers: " + (maxWorkers - workers) + " (" + maxWorkers + "); ports: " + (maxPorts - ports) +
                      " (" + maxPorts + ")" + Environment.NewLine);

            return(sb.ToString());
        }
Ejemplo n.º 29
0
 private void CreatThreadPool_Upload()
 {
     for (int i = 0; i < l_s.Count; i++)
     {
         if (l_s[i].State == 2)
         {
             #region 启动下载目录
             WaitCallback wcb = new WaitCallback(ThreadFunUpload_Directory);
             int          workerThreads, availabeThreads;
             ThreadPool.GetAvailableThreads(out workerThreads, out availabeThreads);
             if (workerThreads > 0)//可用线程数>0
             {
                 ThreadPool.QueueUserWorkItem(wcb, l_s[i]);
             }
             else
             {
                 //to do 可以采取一种策略,让这个任务合理地分配给线程
             }
             #endregion
         }
         else
         {
             #region 启动下载单个文件
             WaitCallback wcb = new WaitCallback(ThreadFun_Upload_File);
             int          workerThreads, availabeThreads;
             ThreadPool.GetAvailableThreads(out workerThreads, out availabeThreads);
             if (workerThreads > 0)//可用线程数>0
             {
                 ThreadPool.QueueUserWorkItem(wcb, l_s[i]);
             }
             else
             {
                 //to do 可以采取一种策略,让这个任务合理地分配给线程
             }
             #endregion
         }
     }
 }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            WorkHandler wh = DoSomething;

            Thread.CurrentThread.Name = "Main Thread";
            var ar = wh.BeginInvoke(20, asyncResult => { Console.WriteLine("DoSomething Done"); }, null);

            for (int i = 0; i < 20; i++)
            {
                IntReturner ir  = GetInteger;
                var         ar2 = ir.BeginInvoke(asyncResult =>
                {
                    Console.WriteLine("GetInteger Done");
                }, null);
            }

            int remainingWorkerThreads, remainingIOThreads;

            ThreadPool.GetAvailableThreads(out remainingWorkerThreads, out remainingIOThreads);
            Console.WriteLine($"While the worker thread is doing its work, here we are in the {Thread.CurrentThread.Name} again. Remaining threads: {remainingWorkerThreads}");

            Console.ReadKey();
        }