public WorkItemsGroup( SmartThreadPool stp, int concurrency, WIGStartInfo wigStartInfo) { if (concurrency <= 0) { throw new ArgumentOutOfRangeException( "concurrency", #if !(WindowsCE) concurrency, #endif "concurrency must be greater than zero"); } _stp = stp; _concurrency = concurrency; _workItemsGroupStartInfo = new WIGStartInfo(wigStartInfo).AsReadOnly(); _workItemsQueue = new PriorityQueue(); Name = "WorkItemsGroup"; // The _workItemsInStpQueue gets the number of currently executing work items, // because once a work item is executing, it cannot be cancelled. _workItemsInStpQueue = _workItemsExecutingInStp; _isSuspended = _workItemsGroupStartInfo.StartSuspended; }
public WorkItemsGroup(SmartThreadPool stp, int concurrency, WIGStartInfo wigStartInfo) { if (concurrency <= 0) { throw new ArgumentOutOfRangeException("concurrency", concurrency, "concurrency must be greater than zero"); } this._stp = stp; this._concurrency = concurrency; this._workItemsGroupStartInfo = new WIGStartInfo(wigStartInfo); this._workItemsQueue = new PriorityQueue(); this._workItemsInStpQueue = this._workItemsExecutingInStp; }
public void ExceptionType() { SmartThreadPool smartThreadPool = new SmartThreadPool(); var workItemResult = smartThreadPool.QueueWorkItem(new Amib.Threading.Func <int>(ExceptionMethod)); smartThreadPool.WaitForIdle(); Assert.IsInstanceOf <NotImplementedException>(workItemResult.Exception); smartThreadPool.Shutdown(); }
private void btnStop_Click(object sender, System.EventArgs e) { running = false; workItemsProducerThread.Join(); _smartThreadPool.Shutdown(true, 1000); _smartThreadPool.Dispose(); _smartThreadPool = null; GC.Collect(); GC.WaitForPendingFinalizers(); UpdateControls(false); }
/*! * Opens the COM port and creates a thread that will * process all incoming serial data */ public void Open() { //_serialPort.PortName = portName; //_serialPort.BaudRate = baudrate; //_serialPort.Open(); _smartThreadPool = SmartThreadPoolSingleton.GetInstance(); _smartThreadPool.Name = "ReceiveThreadedData"; IWorkItemResult wir = _smartThreadPool.QueueWorkItem( new WorkItemCallback(this.ReceiveThreadedData), _serialPort); }
/// <summary> /// Start /// </summary> /// <param name="setting"></param> /// <param name="serializer"></param> public static void Start(CacheSetting setting, ICacheSerializer serializer) { _serializer = serializer; _entityQueueTimer = new Timer(OnEntitySyncQueue, null, 60, 100); _entityQueueWacher = new Timer(CheckEntityQueue, null, 60, 60000); MessageQueueSection section = GetSection(); InitRedisQueue(section); InitSqlQueue(section); _threadPools = new SmartThreadPool(180 * 1000, 100, 5); _threadPools.Start(); }
public static void Run(SmartThread.Action task1) { SmartThreadPool st = new SmartThreadPool(); IWorkItemResult t1 = st.QueueWorkItem(() => { task1(); }); bool success = SmartThreadPool.WaitAll(new IWorkItemResult[] { t1 }); //if (success) result1 = (int)wir1.Result; st.Shutdown(); }
/// <summary> /// Starts the tasks execution. /// </summary> /// <returns>If has reach the timeout false, otherwise true.</returns> public override bool Start() { base.Start(); m_threadPool = new SmartThreadPool(); try { m_threadPool.MinThreads = MinThreads; m_threadPool.MaxThreads = MaxThreads; var workItemResults = new IWorkItemResult[Tasks.Count]; for (int i = 0; i < Tasks.Count; i++) { var t = Tasks[i]; workItemResults[i] = m_threadPool.QueueWorkItem(new WorkItemCallback(Run), t); } m_threadPool.Start(); // Timeout was reach? if (!m_threadPool.WaitForIdle(Timeout.TotalMilliseconds > int.MaxValue ? int.MaxValue : Convert.ToInt32(Timeout.TotalMilliseconds))) { if (m_threadPool.IsShuttingdown) { return(true); } else { m_threadPool.Cancel(true); return(false); } } foreach (var wi in workItemResults) { Exception ex; wi.GetResult(out ex); if (ex != null) { throw ex; } } return(true); } finally { m_threadPool.Shutdown(true, 1000); m_threadPool.Dispose(); IsRunning = false; } }
public void Initialise(IConfigSource config) { m_proxyurl = config.Configs["Startup"].GetString("HttpProxy"); m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions"); HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384); m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config); int maxThreads = 8; IConfig httpConfig = config.Configs["ScriptsHttpRequestModule"]; if (httpConfig != null) { maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads); m_primBurst = httpConfig.GetFloat("PrimRequestsBurst", m_primBurst); m_primPerSec = httpConfig.GetFloat("PrimRequestsPerSec", m_primPerSec); m_primOwnerBurst = httpConfig.GetFloat("PrimOwnerRequestsBurst", m_primOwnerBurst); m_primOwnerPerSec = httpConfig.GetFloat("PrimOwnerRequestsPerSec", m_primOwnerPerSec); m_httpTimeout = httpConfig.GetInt("RequestsTimeOut", m_httpTimeout); if (m_httpTimeout > 60000) { m_httpTimeout = 60000; } else if (m_httpTimeout < 200) { m_httpTimeout = 200; } } m_pendingRequests = new Dictionary <UUID, HttpRequestClass>(); m_CompletedRequests = new ConcurrentQueue <HttpRequestClass>(); m_RequestsThrottle = new ConcurrentDictionary <uint, ThrottleData>(); m_OwnerRequestsThrottle = new ConcurrentDictionary <UUID, ThrottleData>(); // First instance sets this up for all sims if (ThreadPool == null) { STPStartInfo startInfo = new STPStartInfo() { IdleTimeout = 2000, MaxWorkerThreads = maxThreads, MinWorkerThreads = 0, ThreadPriority = ThreadPriority.Normal, StartSuspended = true, ThreadPoolName = "ScriptsHttpReq" }; ThreadPool = new SmartThreadPool(startInfo); ThreadPool.Start(); } }
private object ThreadPoolRoutine(object state) { if (!(state is UpdateTaskScheduler <TTaskKey, TCallbackArg> .ScheduledTask scheduledTask)) { throw new ArgumentException("Unexpected state object or null", nameof(state)); } try { bool taskExecuted = false; Exception ex1 = (Exception)null; using (LocaleThreadState.EnsurePrimaryLocale()) { if (!SmartThreadPool.get_IsWorkItemCanceled()) { try { taskExecuted = true; this.taskRoutine(scheduledTask.TaskKey); } catch (Exception ex2) { ex1 = ex2; this.log.Error((object)string.Format("Task {0} cought unhandled exception from task routine", (object)scheduledTask), ex2); } } if (scheduledTask.Callbacks != null) { foreach (UpdateTaskScheduler <TTaskKey, TCallbackArg> .ScheduledTaskCallback callback in scheduledTask.Callbacks) { try { callback.Callback(new UpdateTaskScheduler <TTaskKey, TCallbackArg> .ScheduledTaskCallbackEventArgs(scheduledTask.TaskKey, callback.State, ex1, taskExecuted)); } catch (Exception ex2) { this.log.Error((object)string.Format("Task {0} callback failed", (object)scheduledTask), ex2); } } } } } catch (Exception ex) { this.log.Error((object)string.Format("Task {0} cought unhandled exception during task processing", (object)scheduledTask), ex); } finally { lock (this.syncLock) this.ongoingTasks.Remove(scheduledTask); } return((object)null); }
protected override void OnStart(string[] args) { //Load MO to Queue //tinnv 2012-09-19 Viet rieng de chay NON VMG Route <Runon_Route <> 5> Thread worker1 = new Thread(AddtoQueue); worker1.Name = "MyWorker"; worker1.IsBackground = false; worker1.Start(); int concurentThreads = 50; int maxThread = 55; try { concurentThreads = Convert.ToInt32(SMS.Default.ConcurentThread); } catch { concurentThreads = 50; } try { maxThread = Convert.ToInt32(SMS.Default.MaxThread); } catch { maxThread = 55; } try { STPStartInfo stpStartInfo = new STPStartInfo { ThreadPriority = ThreadPriority.Normal, WorkItemPriority = WorkItemPriority.Normal, IdleTimeout = 60000, MaxWorkerThreads = maxThread, MinWorkerThreads = 0, EnableLocalPerformanceCounters = false }; this._smartThreadPool = new SmartThreadPool(stpStartInfo); this._smartThreadPool.WaitForIdle(); this._workItemsGroup = this._smartThreadPool.CreateWorkItemsGroup(concurentThreads); this._workItemsGroup.WaitForIdle(); this.workItemsProducerThread = new Thread(new ThreadStart(this.WorkItemsProducer)); this.workItemsProducerThread.IsBackground = false; this.workItemsProducerThread.Start(); } catch (Exception ex) { _logger.Error(string.Concat("Error - VNM_VClip_Charging.SendMT.Onstart: ", ex.Message)); _logger.Error(string.Concat("Error - VNM_VClip_Charging.SendMT.Onstart: ", ex.StackTrace)); } }
static ScreenClientHandler() { smartThreadPool = new SmartThreadPool(); smartThreadPool.Start(); int start = 65, end = 90; while (start <= end) { listIndex.Add(((char)start).ToString()); start++; } }
private void CheckSinglePriority(ThreadPriority threadPriority) { STPStartInfo stpStartInfo = new STPStartInfo(); stpStartInfo.ThreadPriority = threadPriority; SmartThreadPool stp = new SmartThreadPool(stpStartInfo); IWorkItemResult wir = stp.QueueWorkItem(new WorkItemCallback(GetThreadPriority)); ThreadPriority currentThreadPriority = (ThreadPriority)wir.GetResult(); Assert.AreEqual(threadPriority, currentThreadPriority); }
public void GoodPostExecute() { SmartThreadPool stp = new SmartThreadPool(); stp.QueueWorkItem( new WorkItemCallback(DoWork), null, new PostExecuteWorkItemCallback(DoPostExecute)); stp.WaitForIdle(); stp.Shutdown(); }
private void materialRaisedButton12_Click(object sender, EventArgs e) { stopTime = System.DateTime.Now; running = false; workItemsProducerThread.Join(); _smartThreadPool.Shutdown(true, 1000); _smartThreadPool.Dispose(); _smartThreadPool = null; GC.Collect(); GC.WaitForPendingFinalizers(); UpdateControls(false); }
void Start() { planetCount = spaceGeneral.spaceDB.minPlanetCount; planetList = new ConcurrentDictionary <Vector3Int, Planet>(); // Запускается поток, ищущий планеты smartThreadPool = new SmartThreadPool(); smartThreadPool.QueueWorkItem(PlanetListener); // Запускается корутина, отдающая планеты в ScreenManager StartCoroutine(PlanetReturning(returnTime)); }
/// <summary> /// Break |list| into slices of at least |minChunkSize| and schedule them on a thread pool. /// |action| is executed on each individual item. /// </summary> public static void ParallelDo <T>(this IList <T> list, Action <T> action, int minChunkSize = DefaultMinChunkSize, SmartThreadPool threadPool = null) { list.ParallelDo( (chunk) => { foreach (var elem in chunk) { action(elem); } }, minChunkSize, threadPool); }
private void BtnSave_Click(object sender, EventArgs e) { btnSave.Enabled = false; var save = new StringBuilder($"\r\n==当前文件夹/前缀缩写:{shorten}\r\n目录列表:\r\n"); var wait = waitQueue.ToArray(); waitQueue.Add(single.QueueWorkItem(() => { try { SmartThreadPool.WaitAll(wait); waitQueue.RemoveAll(q => wait.Contains(q)); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); } var p = Parallel.For(0, clistDirs.Items.Count, i => save.Append(clistDirs.Items[i] + "\r\n")); while (!p.IsCompleted) { Thread.Sleep(1000); } save.Append("\r\n文件列表:\r\n"); p = Parallel.For(0, listBrowse.Items.Count, i => save.Append(listBrowse.Items[i] + "\r\n")); while (!p.IsCompleted) { Thread.Sleep(1000); } save.Append("\r\n缺失列表:\r\n"); p = Parallel.For(0, listLost.Items.Count, i => save.Append(listLost.Items[i] + "\r\n")); while (!p.IsCompleted) { Thread.Sleep(1000); } save.Append("\r\n报告:\r\n"); save.Append(lblStatus.Text); var writer = saveFileFullName.AppendText(); var reader = new StringReader(save.ToString() + $"\r\n{DateTime.Now}完成==\r\n"); int len = 4096; char[] strToWrite = new char[len]; while (0 < (len = reader.Read(strToWrite, 0, 4096))) { writer.Write(strToWrite, 0, len); } writer.Close(); reader.Close(); save.Clear(); })); btnSave.Enabled = true; }
public async Task Execute(IJobExecutionContext context) { if (!IsRunning) { IsRunning = true; OnStart(context); var task = Task.Factory.StartNew(() => { var requests = GetRequests(); var stpStartInfo = new STPStartInfo { IdleTimeout = 3000, MaxWorkerThreads = MaxWorkerThreads, MinWorkerThreads = 0 }; var pool = new SmartThreadPool(stpStartInfo); var waits = new List <IWorkItemResult>(); foreach (var fr in requests) { if (fr.Request.Headers.Count(m => m.Name == "Referer") == 0) { fr.Request.Headers.Add(new WebHeader("Referer", fr.Request.Uri.AbsoluteUri)); } var item = pool.QueueWorkItem((u) => { var response = DoTask((Request)u.Request); Save(u, response); }, fr); waits.Add(item); } SmartThreadPool.WaitAll(waits.ToArray()); pool.Shutdown(true, 1000); pool.Dispose(); pool = null; waits.Clear(); }); await task; IsRunning = false; } }
private ContentQueue() { queue = new MessageQueue <string>(); queue.ContentChanged += queue_ContentChanged; stpStartInfo = new STPStartInfo { IdleTimeout = 3000, MaxWorkerThreads = 8, MinWorkerThreads = 0 }; pool = new SmartThreadPool(stpStartInfo); }
public void QueueWorkItem_WhenMaxIsNull_Queues() { var info = new STPStartInfo { MaxQueueLength = null, }; var pool = new SmartThreadPool(info); pool.Start(); var workItem = pool.QueueWorkItem <object>(ReturnNull); // If rejected, an exception would have been thrown instead. Assert.IsTrue(workItem.GetResult() == null); }
public static void RunThreads(Action <byte[], byte[], int> function, List <byte[]> arrayList, byte[] arrayRgbColorBytes, int threadsAmount) { SmartThreadPool smartThreadPool = new SmartThreadPool(60 * 1000, threadsAmount, threadsAmount); foreach (var byteArray in arrayList) { smartThreadPool.QueueWorkItem(function, byteArray, arrayRgbColorBytes, byteArray.Length); } smartThreadPool.Start(); smartThreadPool.WaitForIdle(); smartThreadPool.Shutdown(); }
public void DoWork(int[] numbers) { SmartThreadPool smartThreadPool = new SmartThreadPool(); // Queue the work item IWorkItemResult <double> wir = smartThreadPool.QueueWorkItem(new Func <int[], double>(CalcAverage), numbers); // Do some other work here // Get the result of the operation double average = wir.Result; smartThreadPool.Shutdown(); }
private void InitSTP() { STPStartInfo stpStartInfo = new STPStartInfo { StartSuspended = true, MaxWorkerThreads = ((int)spinCon6.Value), IdleTimeout = int.Parse(spinIdleTimeout.Text) * 1000, }; if (_useWindowsPerformanceCounters) { stpStartInfo.PerformanceCounterInstanceName = "WIG Test SmartThreadPool"; } else { stpStartInfo.EnableLocalPerformanceCounters = true; } _smartThreadPool = new SmartThreadPool(stpStartInfo); WIGStartInfo wigStartInfo = new WIGStartInfo() { FillStateWithArgs = true, }; _wig1 = _smartThreadPool.CreateWorkItemsGroup((int)spinCon1.Value, wigStartInfo); _wig2 = _smartThreadPool.CreateWorkItemsGroup((int)spinCon2.Value, wigStartInfo); _wig3 = _smartThreadPool.CreateWorkItemsGroup((int)spinCon3.Value, wigStartInfo); spinCon1.Tag = _wig1; spinCon2.Tag = _wig2; spinCon3.Tag = _wig3; spinCon6.Tag = _smartThreadPool; comboWIPriority1.SelectedIndex = 1; comboWIPriority2.SelectedIndex = 1; comboWIPriority3.SelectedIndex = 1; comboWIPriority6.SelectedIndex = 1; _wigEntries = new WigEntry[] { new WigEntry(_wig1, queueUsageControl1, lblStatus1), new WigEntry(_wig2, queueUsageControl2, lblStatus2), new WigEntry(_wig3, queueUsageControl3, lblStatus3), }; for (int i = 0; i < _lastIndex.Length; i++) { _lastIndex[i] = 1; } }
public void GoodPostExecute() { SmartThreadPool smartThreadPool = new SmartThreadPool(); IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(int.MaxValue); workItemsGroup.QueueWorkItem( new WorkItemCallback(DoWork), null, new PostExecuteWorkItemCallback(DoPostExecute)); workItemsGroup.WaitForIdle(); smartThreadPool.Shutdown(); }
public static bool Init(bool useSmartThredPool) { if (Pool == null) { STPStartInfo param = new STPStartInfo(); param.MinWorkerThreads = 2; param.MaxWorkerThreads = 50; param.ThreadPoolName = "LibOpenMetaverse Main ThreadPool"; param.AreThreadsBackground = true; Pool = new SmartThreadPool(param); } return(true); }
private bool WaitForMinThreadsValue(SmartThreadPool smartThreadPool, int minThreadsCount, int timeout) { DateTime end = DateTime.Now + new TimeSpan(0, 0, 0, 0, timeout); bool success = false; while (DateTime.Now <= end && !success) { success = (smartThreadPool.ActiveThreads == minThreadsCount); Thread.Sleep(10); } return(success); }
public void ChainedDelegatesCallback() { SmartThreadPool stp = new SmartThreadPool(); WorkItemCallback workItemCallback = new WorkItemCallback(DoWork); workItemCallback += new WorkItemCallback(DoWork); stp.QueueWorkItem(workItemCallback); stp.WaitForIdle(); stp.Shutdown(); }
public void SetMaxQueueLength_FromNonZeroValueToZero_DisablesQueueing() { Assert.Throws <QueueRejectedException>(() => { var info = new STPStartInfo { MinWorkerThreads = 1, MaxWorkerThreads = 1, MaxQueueLength = 1, }; var pool = new SmartThreadPool(info); pool.Start(); try { pool.QueueWorkItem(SleepForOneSecond); // Picked up by waiter. pool.QueueWorkItem(SleepForOneSecond); // Queued. } catch (QueueRejectedException e) { throw new Exception("Caught QueueRejectedException too early: ", e); } try { pool.QueueWorkItem(SleepForOneSecond); } catch (QueueRejectedException) { // Expected Assert.True(true); } pool.MaxQueueLength = 0; Thread.Sleep(2100); // Let the work items complete. try { pool.QueueWorkItem(SleepForOneSecond); // Picked up by waiter. } catch (QueueRejectedException e) { throw new Exception("Caught QueueRejectedException too early: ", e); } pool.QueueWorkItem(SleepForOneSecond); // Rejected (max queue length is zero). }); }
internal SipContextSource(IPEndPoint ipEndPoint, SmartThreadPool threadPool, SipMessageFactory messageFactory, SipHeaderFactory headerFactory) { Check.Require(ipEndPoint, "ipEndPoint"); Check.Require(threadPool, "threadPool"); Check.Require(messageFactory, "messageFactory"); Check.Require(headerFactory, "headerFactory"); _ipEndPoint = ipEndPoint; _threadPool = threadPool; _messageFactory = messageFactory; _headerFactory = headerFactory; _logger.Trace("Constructor called."); _sender = new DatagramSender(_ipEndPoint); }
private void RunDownloadPool(WorkType work) { //Setup downloadPool downloadPool = SetupSmartThreadPool(settings.DownloadPoolThreads); //Select the items to add to the queue addDownloadTasksToQueue(work); downloadPool.Start(); bool success = SmartThreadPool.WaitAll(results.ToArray()); downloadPool.Shutdown(); WriteStatus("Download Pool Completed, succeeded = " + success.ToString()); }
public WorkItemsGroup( SmartThreadPool stp, int concurrency, WIGStartInfo wigStartInfo) { if (concurrency <= 0) { throw new ArgumentOutOfRangeException("concurrency", concurrency, "concurrency must be greater than zero"); } _stp = stp; _concurrency = concurrency; _workItemsGroupStartInfo = new WIGStartInfo(wigStartInfo); _workItemsQueue = new PriorityQueue(); // The _workItemsInStpQueue gets the number of currently executing work items, // because once a work item is executing, it cannot be cancelled. _workItemsInStpQueue = _workItemsExecutingInStp; }
public ThreadEntry(SmartThreadPool stp) { _associatedSmartThreadPool = stp; _creationTime = TimestampNonce.Now; _lastAliveTime = DateTime.MinValue; }