static void PrintThreadsInformation() { var minWorker = -1; var minCompletion = -1; ThreadPool.GetMinThreads(out minWorker, out minCompletion); var maxWorker = -1; var maxCompletion = -1; ThreadPool.GetMaxThreads(out maxWorker, out maxCompletion); var availableWorker = -1; var availableCompletion = -1; ThreadPool.GetAvailableThreads(out availableWorker, out availableCompletion); System.Console.WriteLine("####################"); System.Console.WriteLine("MinWorker: '{0}', MinCompletion: '{1}'", minWorker, minCompletion); System.Console.WriteLine("MaxWorker: '{0}', MaxCompletion: '{1}'", maxWorker, maxCompletion); System.Console.WriteLine("AvailableWorker: '{0}', AvailableCompletion: '{1}'", availableWorker, availableCompletion); System.Console.WriteLine("####################{0}", Environment.NewLine); }
public static void SetMinMaxThreadsTest_ChangedInDotNetCore() { int minw, minc, maxw, maxc; ThreadPool.GetMinThreads(out minw, out minc); ThreadPool.GetMaxThreads(out maxw, out maxc); try { Assert.True(ThreadPool.SetMinThreads(0, 0)); VerifyMinThreads(1, 1); Assert.False(ThreadPool.SetMaxThreads(0, 1)); Assert.False(ThreadPool.SetMaxThreads(1, 0)); VerifyMaxThreads(maxw, maxc); } finally { Assert.True(ThreadPool.SetMaxThreads(maxw, maxc)); VerifyMaxThreads(maxw, maxc); Assert.True(ThreadPool.SetMinThreads(minw, minc)); VerifyMinThreads(minw, minc); } }
/// <summary> /// 设置线程池的最大工作线程数和空闲辅助线程的最小数目 /// </summary> /// <param name="minNum">初始空闲辅助线程的最小数目</param> /// <param name="maxNum">线程池的最大工作线程数</param> public static void SetThreadNumByThreadPool(int minNum, int maxNum) { //检测参数的有效性 if (maxNum < minNum || minNum <= 0) { throw new Exception("入参无效"); } //定义线程数 int threadNum; //线程池异步I/O线程的最大数目 int ioNum; //获取最小的线程数 ThreadPool.GetMinThreads(out threadNum, out ioNum); //设置最小线程数 ThreadPool.SetMinThreads(minNum, ioNum); //获取最大的线程数 ThreadPool.GetMaxThreads(out threadNum, out ioNum); //设置最大的线程数 ThreadPool.SetMaxThreads(maxNum, ioNum); }
// 取得執行緒集區內的相關設定參數 static void GetThreadPoolInformation(ThreadPoolInformation threadPoolInformation) { int workerThreads; int completionPortThreads; // 傳回之執行緒集區的現在還可以容許使用多少的執行緒數量大小 ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); threadPoolInformation.AvailableWorkerThreads = workerThreads; threadPoolInformation.AvailableCompletionPortThreads = completionPortThreads; // 擷取可並行使用之執行緒集區的要求數目。 超過該數目的所有要求會繼續佇列,直到可以使用執行緒集區執行緒為止 ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); threadPoolInformation.MaxWorkerThreads = workerThreads; threadPoolInformation.MaxCompletionPortThreads = completionPortThreads; // 在切換至管理執行緒建立和解構的演算法之前,擷取執行緒集區隨著提出新要求,視需要建立的執行緒最小數目。 ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); threadPoolInformation.MinWorkerThreads = workerThreads; threadPoolInformation.MinCompletionPortThreads = completionPortThreads; // 如果目前電腦包含多個處理器群組,則這個屬性會傳回可供 Common Language Runtime (CLR) 使用的邏輯處理器數目 threadPoolInformation.ProcessorCount = System.Environment.ProcessorCount; }
public InterfaceFileWatcher() { string name = DateTime.Now.Year + "-" + DateTime.Now.Month.ToString().PadLeft(2, '0'); Log.Instance.LogPath = $@"{LogPath}\{name}"; Log.Instance.LogFileName = "ADE.Services.Monitor"; InitializeComponent(); //CheckExistingFiles(); //Watcher = new MyFileSystemWatcher(); // NUEVO MÉTODO // 2017-07-21 try { MaxNumberOfThreads = int.Parse(ConfigurationManager.AppSettings["MaxNumberOfThreads"]); Log.WriteLine($"Se ha configurado un máximo de {MaxNumberOfThreads} threads para el servicio"); int w; int c; ThreadPool.GetMinThreads(out w, out c); ThreadPool.SetMinThreads(MaxNumberOfThreads, c); // Write the numbers of minimum threads //Log.WriteLine($"Minimun=> {w}, {c}"); } catch (Exception ConvException) { MaxNumberOfThreads = 40; Log.WriteLine($"no se ha encontrado un valor de threads"); Log.WriteLine($"Se ha configurado un máximo de {MaxNumberOfThreads} threads para el servicio, valor por defecto"); int w; int c; ThreadPool.GetMinThreads(out w, out c); ThreadPool.SetMinThreads(MaxNumberOfThreads, c); //Log.WriteLine("Error al obtener el Numero Maximo de Threads: " + ConvException.Message); } }
static void Main(string[] args) { Console.WriteLine($"Is main thread a thread pool thread? {Thread.CurrentThread.IsThreadPoolThread}"); Employee employee = new Employee { Name = "Orestis", CompanyName = "Microsoft" }; ThreadPool.QueueUserWorkItem(new WaitCallback(DisplayEmployeeInfo), employee); // Set the max number of threads in the thread pool - 1st way // Get the number of processors in the host machine //var processorsCount = Environment.ProcessorCount; //ThreadPool.SetMaxThreads(processorsCount * 2, processorsCount * 2); // Set the max number of threads in the thread pool - 2nd way int workerThreads = 0; int completionPortThreads = 0; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); // This is just an example of being able to set the maximum threads. There is a bit of a caveat here. // That number could be anything. You can even say thousand, but it wouldn't really matter. // At one point of time, you'll only have a certain amount of threads that can do the processing. // Everything else will have to wait. But this is important because you want to set a max number of threads. // If you know what your usage is going to look like, you want to keep it in a very controlled manner. // Of course you have the min threads, which is equal to the number of different CPUs in the current maching and that's the minimum it gets. // But the fact that you have the power to set it, it makes it so much better because now, you have less overhead with dealing with threads. ThreadPool.SetMaxThreads(workerThreads * 2, completionPortThreads * 2); Console.WriteLine($"Is main thread a thread pool thread? {Thread.CurrentThread.IsThreadPoolThread}"); Console.ReadLine(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); //RouteConfig.RegisterHandler(RouteTable.Routes); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); int minWorker, minIOC; // Get the current settings. ThreadPool.GetMinThreads(out minWorker, out minIOC); //服务器设置最小的进程中线程为240,因为是8核cpu。单核30,8核是:8*30 ThreadPool.SetMinThreads(30, minIOC); //if (!Utility.IsLocal()) //{ // ThreadPool.SetMinThreads(30, minIOC); //} Thread th = new Thread(() => { LMSoft.Web.Hubs.RabbitMQInstance.Listening(); }); th.Start(); Thread th1 = new Thread(() => { LMSoft.Web.Hubs.RabbitMQInstance.ListeningRabbitMQTest(); }); th1.Start(); // 定时工作任务 _worker = new QuartzWorker(); Hubs.TheTask.QuestionsLibraryAndSortListRightPushWork questionsLibraryAndSortWork = new Hubs.TheTask.QuestionsLibraryAndSortListRightPushWork(); _worker.AddWork(questionsLibraryAndSortWork); Hubs.TheTask.DeleteExamWork deleteExamWork = new Hubs.TheTask.DeleteExamWork(); _worker.AddWork(deleteExamWork); _worker.Start(); }
public void Init(string IP, int Port, SocketTcpServerEvent SocketTcpServerEvent, int MessageNum, int MessageTime) { for (int i = 0; i < counters.Length; i++) { counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString()); } ThreadPool.GetMinThreads(out threadNum, out threadNum); connectErrorNum = 0; this.SocketTcpServerEvent = SocketTcpServerEvent; readEventPool = new SocketAsyncEventArgsPool(100000); //readDataBuf = new Dictionary<Socket, ReadDataModel>(); writeEventPool = new SocketAsyncEventArgsPool(100000); socketDic = new Dictionary <Socket, SocketModel>(); //writeEvent = new Dictionary<Socket, SocketAsyncEventArgs>(); //writeDataBuf = new Dictionary<Socket, List<byte[]>>(); //writeType = new Dictionary<Socket, bool>(); //messageThread = new Thread(new ThreadStart(message_Run)); //messageThread.Start(); //messageTime = new Dictionary<Socket, long>(); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //socket.SendBufferSize = 102400000; //socket.ReceiveBufferSize =102400000; socket.NoDelay = false; uint dummy = 0; byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); BitConverter.GetBytes((uint)60000).CopyTo(inOptionValues, Marshal.SizeOf(dummy)); BitConverter.GetBytes((uint)6000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2); socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); socket.Bind(new IPEndPoint(IPAddress.Parse(IP), Port)); socket.Listen(100); connectEvent = new SocketAsyncEventArgs(); connectEvent.DisconnectReuseSocket = false; connectEvent.Completed += connectEvent_Completed; socket.AcceptAsync(connectEvent); }
/// <summary> /// Setup Min Max Threads in ThreadPool /// Show Point procedure /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void StartGrading() { // Setup Min Max Threads in ThreadPool // This should be 1 because cpu is easy to run but HDD disk can not load over 2 threads in 1 time => wrong mark for student // So workerThreads = 1, completionPortThreads = 1; int workerThreads = Constant.MaxThreadPoolSize, completionPortThreads = Constant.MaxThreadPoolSize; ThreadPool.SetMinThreads(workerThreads, completionPortThreads); ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); ThreadPool.SetMaxThreads(workerThreads, completionPortThreads); // Get Point if (!scored) { // Reset to count how many results has been marked. count = 0; // Populate the data source. for (var row = 0; row < ListResults.Count; row++) { var currentResult = ListResults.ElementAt(row); // Prepare 2 first columns scoreGridView.Invoke((MethodInvoker)(() => { scoreGridView.Rows.Add(1); scoreGridView.Rows[row].Cells[0].Value = currentResult.StudentID; scoreGridView.Rows[row].Cells[1].Value = currentResult.PaperNo; })); var input = new Input(row, currentResult); ThreadPool.QueueUserWorkItem(callBack => Grade(input)); } scored = true; } else { MessageBox.Show("Score has already got."); } }
static void Main(string[] args) { #region Test int i1, i2; ThreadPool.GetMaxThreads(out i1, out i2); Console.WriteLine("Max workerThreads :" + i1 + " completionPortThreads:" + i2); ThreadPool.GetMinThreads(out i1, out i2); Console.WriteLine("Min workerThreads:" + i1 + " completionPortThreads:" + i2); Console.WriteLine(" CLR Version: {0} ", Environment.Version); #endregion try { //获取下载地址 var fileInfo = GetFileInfo(getLatestVersionUrl); var latestVersionUrl = fileInfo.DownLoadUrl; //文件名 var fileName = latestVersionUrl.Substring(latestVersionUrl.LastIndexOf('/') + 1); //下载 var flag = FileTool.Download(latestVersionUrl, packageDownloadUrl); //解压 FileTool.DeCompressRar(Path.Combine(packageDownloadUrl, fileName), uncompressUrl); var webSiteUrls = webSiteUrl.Split('|').ToList(); foreach (var webSiteUrl in webSiteUrls) { //删除bin目录 FileTool.DeleteFile(Path.Combine(webSiteUrl, "bin")); //复制 FileTool.CopyFolder(Path.Combine(uncompressUrl, fileName.Remove(fileName.LastIndexOf("."))), webSiteUrl); //改名 FileTool.ReName(Path.Combine(webSiteUrl, fileName.Remove(fileName.LastIndexOf("."))), "bin"); } SetConfigValue("VersionsNumber", fileName); } catch (Exception ex) { } }
void Application_Start(object sender, EventArgs e) { // 启动时记录日志,避免后面影响 var procid = Process.GetCurrentProcess().Id.ToString(); var thid = Thread.CurrentThread.ManagedThreadId.ToString(); var idmsg = "当前进程/线程ID:" + procid + "/" + thid; LogHelper.WriteCustom("App_Start Begin\r\n " + idmsg, "AppStartEnd\\", false); // 注册完整GC通知,在gc回收时记录日志 GCNotification.Register(); // 初始化ip纯真库,用于ip地区判断 // IPLocator.Initialize(Server.MapPath(@"qqwry.dat")); int minworkthreads; int miniocpthreads; ThreadPool.GetMinThreads(out minworkthreads, out miniocpthreads); // 初始化完成记录日志 idmsg += "最小工作线程数/IO线程数:" + minworkthreads.ToString() + "/" + miniocpthreads.ToString(); LogHelper.WriteCustom("App_Start End\r\n " + idmsg, "AppStartEnd\\", false); }
//ta je base in z njo dobimo točen state za več različnih (trenutno 2) variant private static Function ComputeInThreadPoolBase(double _from, double _to, double _resolution, WaitCallback _waitCallback, Func <double, object> _getState) { //si zapomnimo originalno nastavitev int _workerThreads = 0; int _completionPortThreads = 0; ThreadPool.GetMinThreads(out _workerThreads, out _completionPortThreads); //nastavimo glede na settinge ThreadPool.SetMinThreads( EngineDesigner.Common.Properties.Settings.Default.MinWorkerThreadsForThreadPoolOperations, EngineDesigner.Common.Properties.Settings.Default.MinCompletionPortThreadsForThreadPoolOperations); //poskrbimo da je vse na nuli long _numerOfThreadsToComplete = (long)((_to - _from) / _resolution); ComputeFunctionInThreadPoolStateBase.Reset(_numerOfThreadsToComplete); //rešimo funkcijo for (double _x = _from; _x < _to; _x += _resolution) { //zabijemo v threadpool ThreadPool.QueueUserWorkItem(_waitCallback, _getState(_x)); } //čakamo, dokler niso vsi končani ComputeFunctionInThreadPoolStateBase.AllThreadsDone.WaitOne(); //povrnemo originalno nastavitev ThreadPool.SetMinThreads(_workerThreads, _completionPortThreads); //vrnemo Function _functionToReturn = Function.FromPoints(ComputeFunctionInThreadPoolStateBase.Points); return(_functionToReturn); }
static void Main(string[] args) { Console.WriteLine("Is Server GC: " + GCSettings.IsServerGC); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; Console.WriteLine("Compaction mode: " + GCSettings.LargeObjectHeapCompactionMode); Console.WriteLine("Latency mode: " + GCSettings.LatencyMode); GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency; Console.WriteLine("New Latency mode: " + GCSettings.LatencyMode); Console.WriteLine("I'm the server!"); // ThreadPool.SetMaxThreads(16, maxcomplePorts); int maxworkers, minworkers; int maxcomplePorts, mincomplePorts; ThreadPool.GetMaxThreads(out maxworkers, out maxcomplePorts); ThreadPool.GetMinThreads(out minworkers, out mincomplePorts); Console.WriteLine("The threadpool max " + maxworkers + " min " + minworkers); TargetHost = ConfigurationManager.AppSettings["rabbitmqserver"]; _username = ConfigurationManager.AppSettings["username"]; _password = ConfigurationManager.AppSettings["password"]; var t1 = StartRpcServer(); // var t2 = StartRpcServer(); // var t3 = StartRpcServer(); Task.WaitAll(t1); //, t2, t3); Console.WriteLine("All done"); Thread.CurrentThread.Join(); }
public void PrintSummaryThreadCounts() { int ioThreads, minIoThreads, maxIoThreads, workerThreads, minWorkerThreads, maxWorkerThreads, threadCount, processThreadCount; ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIoThreads); ThreadPool.GetMinThreads(out minWorkerThreads, out minIoThreads); ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads); threadCount = ThreadPool.ThreadCount; processThreadCount = Process.GetCurrentProcess().Threads.Count; TotalUseWorkerThreads = maxWorkerThreads - workerThreads; TotalUseIocpThreads = maxIoThreads - ioThreads; TotalProcessUseThreads = processThreadCount; TotalThreadPoolUseThreads = threadCount; #region 輸出執行緒使用情況 Console.WriteLine($"Worker Threads : {TotalUseWorkerThreads}"); Console.WriteLine($"IO Threads : {TotalUseIocpThreads}"); Console.WriteLine($"Total Process Used Threads : {TotalProcessUseThreads}"); Console.WriteLine($"Total ThreadPool Used Threads : {TotalThreadPoolUseThreads}"); Console.WriteLine(); #endregion }
/// <summary> /// 加入线程池的任务的执行顺序并不一定是加入的顺序 /// </summary> public static void Test() { int workerThreads = 0; int completionPortThreads = 0; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); Console.WriteLine(String.Format("线程池默认最小线程数:{0} - {1}", workerThreads, completionPortThreads)); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); Console.WriteLine(String.Format("线程池默认最大线程数:{0} - {1}", workerThreads, completionPortThreads)); ThreadPool.SetMinThreads(5, 5); ThreadPool.SetMaxThreads(12, 12); Stopwatch watch = new Stopwatch(); watch.Start(); WaitCallback callback = index => { Console.WriteLine(String.Format("{0}:Task {1} started", watch.Elapsed, index)); Thread.Sleep(10000); Console.WriteLine(String.Format("{0}:Task {1} finished", watch.Elapsed, index)); }; for (int i = 0; i < 20; i++) { ThreadPool.QueueUserWorkItem(callback, i); } Thread thread = new Thread(ScanThreadTool); thread.Start(); Console.ReadKey(); }
public static void SubMain() { // 不断加入任务 for (int i = 0; i < 8; i++) { ThreadPool.QueueUserWorkItem(state => { Thread.Sleep(100); Console.WriteLine(""); }); } for (int i = 0; i < 8; i++) { ThreadPool.QueueUserWorkItem(state => { Thread.Sleep(TimeSpan.FromSeconds(1)); Console.WriteLine(""); }); } Console.WriteLine(" 此计算机处理器数量:" + Environment.ProcessorCount); // 工作项、任务代表同一个意思 Console.WriteLine(" 当前线程池存在线程数:" + ThreadPool.ThreadCount); Console.WriteLine(" 当前已处理的工作项数:" + ThreadPool.CompletedWorkItemCount); Console.WriteLine(" 当前已加入处理队列的工作项数:" + ThreadPool.PendingWorkItemCount); int count; int ioCount; ThreadPool.GetMinThreads(out count, out ioCount); Console.WriteLine($" 默认最小辅助线程数:{count},默认最小异步IO线程数:{ioCount}"); ThreadPool.GetMaxThreads(out count, out ioCount); Console.WriteLine($" 默认最大辅助线程数:{count},默认最大异步IO线程数:{ioCount}"); Console.ReadKey(); }
public HttpServer(int maxThreads = 1024) { InitResources(); int workerThreadsMin, completionPortThreadsMin; ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin); int workerThreadsMax, completionPortThreadsMax; ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax); ThreadPool.SetMinThreads(workerThreadsMax, completionPortThreadsMin + maxThreads + 15); _workers = new Task[maxThreads]; _queueLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); _queue = new Queue <HttpListenerContext>(); _stop = new ManualResetEvent(false); _ready = new ManualResetEvent(false); // _listenerTask = new Task(HandleRequest); _listenerThread = new Thread(HandleRequest); _listener = new HttpListener(); _listener.IgnoreWriteExceptions = true; }
static void Main(string[] args) { int workthreadnumber; int iothreadnumber; ThreadPool.GetMinThreads(out workthreadnumber, out iothreadnumber); Console.WriteLine("maxworkthreadnumber is " + workthreadnumber + ",maxworkthreadnumber is " + iothreadnumber + ""); ThreadPool.GetMaxThreads(out workthreadnumber, out iothreadnumber); Console.WriteLine("minworkthreadnumber is " + workthreadnumber + ",miniothreadnumber is " + iothreadnumber + ""); //ThreadPool.SetMaxThreads(1000, 1000); // 获得线程池中可用的线程,把获得的可用工作者线程数量赋给workthreadnumber变量 // 获得的可用I/O线程数量给iothreadnumber变量 ThreadPool.GetAvailableThreads(out workthreadnumber, out iothreadnumber); Console.WriteLine("workthreadnumber is " + workthreadnumber + ",iothreadnumber is " + iothreadnumber + ""); for (int i = 0; i < 1200; i++) { ThreadApp app = new ThreadApp(); app.TheadId = $"TheadId_{i}"; Console.WriteLine("Create Thread is " + app.TheadId); //app.ThreadPoolStart(); app.TaskStart(); } Console.ReadKey(); }
static void MaxThreadExample() { int maxThread, completeThread; ThreadPool.GetMaxThreads(out maxThread, out completeThread); Console.WriteLine("Max Thread : {0}, Complete Thread : {1}", maxThread, completeThread); ThreadPool.GetMinThreads(out maxThread, out completeThread); Console.WriteLine("Min Thread : {0}, Complete Thread : {1}", maxThread, completeThread); ThreadPool.GetAvailableThreads(out maxThread, out completeThread); Console.WriteLine("Avl Thread : {0}, Complete Thread : {1}", maxThread, completeThread); Console.WriteLine("*********************"); Task.Run(() => Parallel.For(0, 10, i => Thread.Sleep(2000))); Task.Run(() => Thread.Sleep(2000)); Task.Run(() => Thread.Sleep(2000)); Task.Run(() => Thread.Sleep(2000)); Task.Run(() => Thread.Sleep(2000)); //Thread.Sleep(10000); ThreadPool.GetMaxThreads(out maxThread, out completeThread); Console.WriteLine("Max Thread : {0}, Complete Thread : {1}", maxThread, completeThread); ThreadPool.GetMinThreads(out maxThread, out completeThread); Console.WriteLine("Min Thread : {0}, Complete Thread : {1}", maxThread, completeThread); ThreadPool.GetAvailableThreads(out maxThread, out completeThread); Console.WriteLine("Avl Thread : {0}, Complete Thread : {1}", maxThread, completeThread); }
private static void SetMinThreadsTo0Test() { int minw, minc, maxw, maxc; ThreadPool.GetMinThreads(out minw, out minc); ThreadPool.GetMaxThreads(out maxw, out maxc); try { Assert.True(ThreadPool.SetMinThreads(0, minc)); Assert.True(ThreadPool.SetMaxThreads(1, maxc)); int count = 0; var done = new ManualResetEvent(false); WaitCallback callback = null; callback = state => { ++count; if (count > 100) { done.Set(); } else { ThreadPool.QueueUserWorkItem(callback); } }; ThreadPool.QueueUserWorkItem(callback); done.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds); } finally { Assert.True(ThreadPool.SetMaxThreads(maxw, maxc)); Assert.True(ThreadPool.SetMinThreads(minw, minc)); } }
static void Main() { Console.WriteLine("Hello ThreadPool!"); var stopwatch = new Stopwatch(); stopwatch.Start(); // DEMO: add task to ThreadPool queue ThreadPool.QueueUserWorkItem(FindPrimes, 1..100_000); ThreadPool.QueueUserWorkItem(FindPrimes, 100_000..150_000); ThreadPool.QueueUserWorkItem(FindPrimes, 150_000..200_000); // DEMO: ThreadPool working threads changes Thread.Sleep(500); ThreadPool.GetMaxThreads(out var worker, out var io); Console.WriteLine($"MaxThreads : {worker}, {io}"); ThreadPool.GetMinThreads(out worker, out io); Console.WriteLine($"MinThreads : {worker}, {io}"); ThreadPool.GetAvailableThreads(out worker, out io); Console.WriteLine($"AvailableThreads : {worker}, {io}"); // DEMO: waiting for thread-sync counter Waiter.Wait(); stopwatch.Stop(); // DEMO: ThreadPool working threads changes Thread.Sleep(500); ThreadPool.GetAvailableThreads(out worker, out io); Console.WriteLine($"AvailableThreads : {worker}, {io}"); Console.WriteLine("Elapsed total : {0}", stopwatch.Elapsed); }
/// <summary> /// Sets the min/max values for the ThreadPool. /// </summary> /// <param name="minThreadCount">The minimum number of worker threads that can be active concurrently.</param> /// <param name="maxThreadCount">The maximum number of worker threads that can be active concurrently.</param> private static void SetThreadPool(int minThreadCount, int maxThreadCount) { int minWorker, minIO; ThreadPool.GetMinThreads(out minWorker, out minIO); Console.WriteLine(minThreadCount); if (minThreadCount != 0) { if (!ThreadPool.SetMinThreads(minThreadCount, minIO)) { throw new Exception("Failed to set the minimum thread count."); } } if (maxThreadCount != 0) { if (!ThreadPool.SetMaxThreads(maxThreadCount, minIO)) { throw new Exception("Failed to set the maximum thread count."); } } }
public string SetThreadPool(int value1, int value2) { ThreadPool.SetMinThreads(value1, value2); string result = "OK"; 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 = "OK " + $"AW:{workerThreadsAvailable} AC:{completionPortThreadsAvailable}" + $" MaxW:{workerThreadsMax} MaxC:{completionPortThreadsMax}" + $" MinW:{workerThreadsMin} MinC:{completionPortThreadsMin} "; return(result); }
public static bool SetMinThreads(int threadCount) { int workerMin, workerMax, workerA, completionPort; ThreadPool.GetAvailableThreads(out workerA, out completionPort); ThreadPool.GetMaxThreads(out workerMax, out completionPort); ThreadPool.GetMinThreads(out workerMin, out completionPort); //CodeSite.Send("workerA", workerA); //CodeSite.Send("workerMax", workerMax); //CodeSite.Send("workerMin", workerMin); int worker = workerMax - workerA + threadCount + 200; //CodeSite.Send("worker", worker); if (worker > workerMin) { worker = Math.Min(worker, workerMax); CodeSite.Send("worker", worker); return(ThreadPool.SetMinThreads(worker, completionPort)); } else { return(true); } }
private static IEnumerable <DocumentBuildParameters> ConfigToParameter(BuildJsonConfig config, TemplateManager templateManager, ChangeList changeList, string baseDirectory, string outputDirectory, string templateDir) { var parameters = new DocumentBuildParameters { OutputBaseDir = outputDirectory, ForceRebuild = config.Force ?? false, ForcePostProcess = config.ForcePostProcess ?? false }; if (config.GlobalMetadata != null) { parameters.Metadata = config.GlobalMetadata.ToImmutableDictionary(); } if (config.FileMetadata != null) { parameters.FileMetadata = ConvertToFileMetadataItem(baseDirectory, config.FileMetadata); } if (config.PostProcessors != null) { parameters.PostProcessors = config.PostProcessors.ToImmutableArray(); } parameters.ExternalReferencePackages = GetFilesFromFileMapping( GlobUtility.ExpandFileMapping(baseDirectory, config.ExternalReference)) .ToImmutableArray(); if (config.XRefMaps != null) { parameters.XRefMaps = config.XRefMaps.ToImmutableArray(); } if (!config.NoLangKeyword) { parameters.XRefMaps = parameters.XRefMaps.Add("embedded:docfx/langwordMapping.yml"); } string outputFolderForDebugFiles = null; if (!string.IsNullOrEmpty(config.OutputFolderForDebugFiles)) { outputFolderForDebugFiles = Path.Combine(baseDirectory, config.OutputFolderForDebugFiles); } var applyTemplateSettings = new ApplyTemplateSettings(baseDirectory, outputDirectory, outputFolderForDebugFiles, config.EnableDebugMode ?? false) { TransformDocument = config.DryRun != true, }; applyTemplateSettings.RawModelExportSettings.Export = config.ExportRawModel == true; if (!string.IsNullOrEmpty(config.RawModelOutputFolder)) { applyTemplateSettings.RawModelExportSettings.OutputFolder = Path.Combine(baseDirectory, config.RawModelOutputFolder); } applyTemplateSettings.ViewModelExportSettings.Export = config.ExportViewModel == true; if (!string.IsNullOrEmpty(config.ViewModelOutputFolder)) { applyTemplateSettings.ViewModelExportSettings.OutputFolder = Path.Combine(baseDirectory, config.ViewModelOutputFolder); } parameters.ApplyTemplateSettings = applyTemplateSettings; parameters.TemplateManager = templateManager; if (config.MaxParallelism == null || config.MaxParallelism.Value <= 0) { parameters.MaxParallelism = Environment.ProcessorCount; } else { parameters.MaxParallelism = config.MaxParallelism.Value; int wt, cpt; ThreadPool.GetMinThreads(out wt, out cpt); if (wt < parameters.MaxParallelism) { ThreadPool.SetMinThreads(parameters.MaxParallelism, cpt); } } if (config.MarkdownEngineName != null) { parameters.MarkdownEngineName = config.MarkdownEngineName; } if (config.MarkdownEngineProperties != null) { parameters.MarkdownEngineParameters = config.MarkdownEngineProperties.ToImmutableDictionary(); } if (config.CustomLinkResolver != null) { parameters.CustomLinkResolver = config.CustomLinkResolver; } parameters.TemplateDir = templateDir; var fileMappingParametersDictionary = GroupFileMappings(config.Content, config.Overwrite, config.Resource); if (config.LruSize == null) { parameters.LruSize = Environment.Is64BitProcess ? 0x2000 : 0xC00; } else { parameters.LruSize = Math.Max(0, config.LruSize.Value); } foreach (var pair in fileMappingParametersDictionary) { var p = parameters.Clone(); VersionConfig vi; if (config.Versions != null && config.Versions.TryGetValue(pair.Key, out vi)) { if (!string.IsNullOrEmpty(vi.Destination)) { p.VersionDir = vi.Destination; } } p.Files = GetFileCollectionFromFileMapping( baseDirectory, GlobUtility.ExpandFileMapping(baseDirectory, pair.Value.GetFileMapping(FileMappingType.Content)), GlobUtility.ExpandFileMapping(baseDirectory, pair.Value.GetFileMapping(FileMappingType.Overwrite)), GlobUtility.ExpandFileMapping(baseDirectory, pair.Value.GetFileMapping(FileMappingType.Resource))); p.VersionName = pair.Key; p.Changes = GetIntersectChanges(p.Files, changeList); // TODO: move RootTocPath to VersionInfo p.RootTocPath = pair.Value.RootTocPath; yield return(p); } }
public void Should_be_completely_thread_safe_to_avoid_duplicates() { NewId.Next(); Stopwatch timer = Stopwatch.StartNew(); int threadCount = 20; int workerThreads, complete; ThreadPool.GetMinThreads(out workerThreads, out complete); ThreadPool.SetMinThreads(workerThreads + threadCount, complete); var loopCount = 1024 * 1024; int limit = loopCount * threadCount; var ids = new NewId[limit]; var tasks = new List <Task>(); var begin = new TaskCompletionSource <bool>(); for (int threadId = 0; threadId < threadCount; threadId++) { var start = threadId * loopCount; var end = start + loopCount; var task = Task.Factory.StartNew(() => { //begin.Task.Wait(); for (int i = start; i < end; i++) { ids[i] = NewId.Next(); } }); tasks.Add(task); } //begin.SetResult(true); Task.WaitAll(tasks.ToArray()); timer.Stop(); Console.WriteLine("Generated {0} ids in {1}ms ({2}/ms)", limit, timer.ElapsedMilliseconds, limit / timer.ElapsedMilliseconds); Console.WriteLine("Distinct: {0}", ids.Distinct().Count()); var duplicates = ids.GroupBy(x => x).Where(x => x.Count() > 1).ToArray(); Console.WriteLine("Duplicates: {0}", duplicates.Count()); foreach (var newId in duplicates) { Console.WriteLine("{0} {1}", newId.Key, newId.Count()); } }
/// <summary>Returns a detailed human readable string that represents the current configuration. It does not contain every single configuration knob.</summary> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(DeploymentId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" DeploymentId: ").Append(DeploymentId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.TraceConfigurationToString(this)); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return(sb.ToString()); }
static MultiThread() { int maxIOThreads; ThreadPool.GetMinThreads(out minThreads, out maxIOThreads); }
public void TestResponsesFromSingleSourceWithMultipleThreads(int count) { var ending = new AutoResetEvent(false); var source = Observable.Defer(() => { var start = 0; var end = start + count; var engine = CreateEngine(); engine.Listener.ClearBindings(); var serverEndPoint = new IPEndPoint(IPAddress.Loopback, Port.NextId); engine.Listener.AddBinding(serverEndPoint); #if NET452 // IMPORTANT: need to set min thread count so as to boost performance. int minWorker, minIOC; // Get the current settings. ThreadPool.GetMinThreads(out minWorker, out minIOC); var threads = engine.Listener.Bindings.Count; ThreadPool.SetMinThreads(threads + 1, minIOC); #endif engine.Start(); try { const int timeout = 10000; // Uncomment below to reveal wrong sequence number issue. // Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); Parallel.For(start, end, index => { GetRequestMessage message = new GetRequestMessage(index, VersionCode.V2, new OctetString("public"), new List <Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) }); // Comment below to reveal wrong sequence number issue. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); Stopwatch watch = new Stopwatch(); watch.Start(); var response = message.GetResponse(timeout, serverEndPoint, socket); watch.Stop(); Assert.Equal(index, response.RequestId()); } ); } finally { if (SnmpMessageExtension.IsRunningOnWindows) { engine.Stop(); } } return(Observable.Return(0)); }) .RetryWithBackoffStrategy( retryCount: 4, retryOnError: e => e is Messaging.TimeoutException ); source.Subscribe(result => { ending.Set(); }); Assert.True(ending.WaitOne(MaxTimeout)); }
private void HandleDebugThreadpoolSet(string module, string[] args) { if (args.Length != 6) { Notice("Usage: debug threadpool set worker|iocp min|max <n>"); return; } int newThreads; if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads)) { return; } string poolType = args[3]; string bound = args[4]; bool fail = false; int workerThreads, iocpThreads; if (poolType == "worker") { if (bound == "min") { ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMinThreads(newThreads, iocpThreads)) { fail = true; } } else { ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads)) { fail = true; } } } else { if (bound == "min") { ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMinThreads(workerThreads, newThreads)) { fail = true; } } else { ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMaxThreads(workerThreads, newThreads)) { fail = true; } } } if (fail) { Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads); } else { int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads; ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads); ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads); Notice("Min worker threads now {0}", minWorkerThreads); Notice("Min IOCP threads now {0}", minIocpThreads); Notice("Max worker threads now {0}", maxWorkerThreads); Notice("Max IOCP threads now {0}", maxIocpThreads); } }