private void btnPause_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; if (state == ThreadState.Running) // Press Pause Button's { if (Algorithm.Algorithm.GetInstance().Pause()) { state = ThreadState.Suspended; btnStart.Enabled = true; btnPause.Enabled = false; btnPause.Text = "&Pause"; btnStop.Enabled = true; btnStart.Text = "&Resume"; if (ResultForm._setting.AutoSave_OnStopped) { Save(Algorithm.Algorithm.GetInstance().GetBestChromosome()); } } } else if (state == ThreadState.Stopped || state == ThreadState.Aborted) // Press Sava Button's { Save(Algorithm.Algorithm.GetInstance().GetBestChromosome()); btnStart.Enabled = true; btnPause.Enabled = false; btnPause.Text = "&Pause"; btnStop.Enabled = false; } this.Cursor = Cursors.Default; }
public Thread(Closure closure, int stackSize) { ThreadClosure = closure; State = new ThreadState(stackSize); State.CurrentInstruction = new InstructionPointer(closure.Func, closure.ClosedVars, 0); State.CurrentInstruction.InstructionIndex = -1; }
/// <summary> /// Waits for all incoming threads to be in wait() /// methods. /// </summary> public static void AwaitState(ThreadState state, params ThreadClass[] threads) { while (true) { bool done = true; foreach (ThreadClass thread in threads) { if (thread.State != state) { done = false; break; } } if (done) { return; } if (Random().NextBoolean()) { Thread.@Yield(); } else { Thread.Sleep(1); } } }
private readonly ThreadState _threadState; // State of the thread #endregion Fields #region Constructors /// <summary> Constructor. </summary> /// <param name="interval"> The execution interval. </param> /// <param name="action"> The action to execute. </param> public TimedAction(double interval, Action action) { _action = action; _threadState = new ThreadState {IsRunning = false}; _actionTimer = new Timer(interval) {Enabled = false, SynchronizingObject = null}; _actionTimer.Elapsed += OnActionTimer; }
public override bool CanComplete(ThreadState threadState) { // A DelayedUnlock can be completed even if the thread does not // own the lock, then the execution does not affect anything // except that the instruction acts as a barrier preventing // instruction before to be completed after the unlock return true; }
public static ThreadState _1_SimplifyThreadState(ThreadState ts) { // Technique to convert threadstate to one of the 4 most useful values: // Unstarted, Running, WaitSleepJoin, and Stopped return ts & (ThreadState.Unstarted | ThreadState.WaitSleepJoin | ThreadState.Stopped); }
public ThreadSurrogated(Thread thread) { Id = thread.ManagedThreadId; Name = thread.Name; Priority = thread.Priority; State = thread.ThreadState; IsBackground = thread.IsBackground; IsThreadPoolThread = thread.IsThreadPoolThread; }
public override bool CanComplete(ThreadState threadState) { // TODO: (much later) support exception here VMValue_objectinst vinst = (VMValue_objectinst)threadState.GetValue(obj); if(vinst.HoldingLockThreadID != threadState.ThreadID) throw new Exception("Calling pulse on a lock we don't possess"); return true; }
private readonly ThreadState _threadState; // State of the thread #endregion Fields #region Constructors /// <summary> Constructor. </summary> /// <param name="disposeStack">Dispose stack to add itself to</param> /// <param name="interval"> The execution interval. </param> /// <param name="action"> The action to execute. </param> public TimedAction(DisposeStack disposeStack, double interval, Action action) { disposeStack.Push(this); _action = action; _threadState = new ThreadState {IsRunning = false}; _actionTimer = new Timer(interval) {Enabled = false, SynchronizingObject = null}; _actionTimer.Elapsed += OnActionTimer; }
public ThreadTraceInfo(int id, string name, DateTime start, float cpuUsage, TimeSpan totalCpuUsageTime, ThreadState state) { _id = id; _name = name; _start = start; _cpuUsage = cpuUsage; _totalCpuUsageTime = totalCpuUsageTime; _state = state; }
public void Start(Action<Exception> threadFailedHandler) { if (threadFailedHandler != null) ThreadFailed += threadFailedHandler; StartCore(); m_State = ThreadState.Starting; m_Thread.Start(); }
// A lock action can be completed if the lock is free // or it is currently hold by the same thread public override bool CanComplete(ThreadState threadState) { // A DelayedLock can only be completed if the object instance is not locked // or it is already locked by this thread VMValue_objectinst vinst = (VMValue_objectinst)threadState.GetValue(obj); if((vinst.HoldingLockThreadID == threadState.ThreadID) || (vinst.HoldingLockThreadID == -1)) return true; else return false; }
/// <summary> /// 创建线程 /// </summary> /// <param name="name"></param> /// <param name="task"></param> /// <param name="isBackground"></param> /// <param name="apartmentState"></param> public SmartThread(Action task, string name = null, bool isBackground = true, ApartmentState apartmentState = ApartmentState.MTA) { if (task == null) throw new ArgumentNullException("task"); InnerThread = new System.Threading.Thread(()=>task()) { Name = name, IsBackground = isBackground }; InnerThread.SetApartmentState(apartmentState); mutex = new ResetEvent(false); State = ThreadState.NotStarted; }
/// <summary> /// Start executing the robotscript /// </summary> public void executeScript() { try { thread = new Thread(new ThreadStart(scriptexecutor)); thState = thread.ThreadState; thread.Start(); } catch (ThreadStateException) { return; } }
/// <summary> /// Creates a new <seealso cref="DocumentsWriterPerThreadPool"/> with a given maximum of <seealso cref="ThreadState"/>s. /// </summary> public DocumentsWriterPerThreadPool(int maxNumThreadStates) { if (maxNumThreadStates < 1) { throw new System.ArgumentException("maxNumThreadStates must be >= 1 but was: " + maxNumThreadStates); } ThreadStates = new ThreadState[maxNumThreadStates]; NumThreadStatesActive = 0; for (int i = 0; i < ThreadStates.Length; i++) { ThreadStates[i] = new ThreadState(null); } }
private Mission(eTaskType taskType, string missionName, string dllLocation, string className, string launchMethod, string shutDownMethod, int launchInterval, int _errorTryInterval, eMissionStatus missionStatus) { _TaskType = taskType; _MissionName = missionName; _DllLocation = string.Format(@"{0}{1}", System.AppDomain.CurrentDomain.BaseDirectory, dllLocation); ; _ClassName = className; _LaunchMethod = launchMethod; _ShutDownMethod = shutDownMethod; _LaunchInterval = launchInterval; _ErrorTryInterval = _errorTryInterval; _MissionStatus = missionStatus; _MissionOwnerStatus = ThreadState.Unstarted; }
private static string ThreadStateAsString(ThreadState state) { var values = (ThreadState[])Enum.GetValues(typeof(ThreadState)); var extractedValues = new List<string>(); foreach (var value in values) { if ((state & value) == value) { extractedValues.Add(DebuggerBase.Instance.MuiProcessor.GetString(_threadStateMuiIdentifiers[value])); } } return string.Join(", ", extractedValues); }
public ContextSwitch(TraceEvent sw) { // Old thread id & process id this.OldThreadId = (int)sw.PayloadValue(0); this.OldProcessId = (int)sw.PayloadValue(1); this.NewThreadId = (int)sw.PayloadValue(3); this.NewProcessId = (int)sw.PayloadValue(4); this.State = (ThreadState)sw.PayloadValue(13); this.ProcessorNumber = sw.ProcessorNumber; this.TimeStamp = sw.TimeStamp; this.TimeStamp100ns = sw.TimeStamp100ns; // Multiply by 10 to adjust the time as 100ns this.NewThreadWaitTime = (int)sw.PayloadValue(15) * 10; }
// In completion stage, the lock action will actually // set the object's lock field to be locked by this thread public override void Complete(ThreadState threadState) { VMValue_objectinst vinst = (VMValue_objectinst)threadState.GetValue(obj); if(vinst.HoldingLockThreadID == -1) { vinst.HoldingLockThreadID = threadState.ThreadID; vinst.HoldingLockCount = nTimes; } else vinst.HoldingLockCount += nTimes; if(CheckerConfiguration.DoPrintExecution) { Console.WriteLine("Commiting Lock in thread " + threadState.CurrentMethod.Name + " on " + obj); } }
/// <summary> /// ThreadStorageView constructor. /// </summary> /// <param name="applicationId"></param> /// <param name="threadId"></param> /// <param name="state"></param> public ThreadStorageView( string applicationId, int threadId, ThreadState state ) : this(-1, applicationId, null, threadId, state, c_noTimeSet, c_noTimeSet, 0, false) { }
public ServiceController() { _sensor = new WiFiSensor(stopThread: _sensorStop, pauseThread: _sensorPause, playThread: _sensorPlay, output: _sensorOutputLocalizerInput); _localizer = new LocationLocalizer(stopThread: _localizerStop, pauseThread: _localizerPause, playThread: _localizerPlay, input: _sensorOutputLocalizerInput, algorithm: _localizationAlgorithm); _sensorState = ThreadState.Playing; _localizerState = ThreadState.Playing; _sensorThread = new Thread(new ThreadStart(_sensor.WiFiSensorLoop)); _localizerThread = new Thread(new ThreadStart(_localizer.LocationLocalizerLoop)); _sensorThread.IsBackground = true; _localizerThread.IsBackground = true; _sensorThread.Name = "WiFiSensorThread"; _localizerThread.Name = "LocationLocalizerThread"; }
public override void Complete(ThreadState threadState) { VMValue dest = threadState.GetValue(destValue); VMValue src = threadState.GetValue(srcValue); dest.CopyFrom(src); dest.IsConcrete = true; if(CheckerConfiguration.DoPrintExecution) { if(dest is VMValue_int32) Console.Write("Committing load of value {0} ",((VMValue_int32)dest).Value); else if(dest is VMValue_double) Console.Write("Committing load of value {0} ",((VMValue_double)dest).Value); else if(dest is VMValue_object) Console.Write("Committing write of {0}", ((VMValue_object)dest).ClassType); else Console.Write("Committing write of non-displayable value"); Console.WriteLine(" from {0} in {1}", sourceInstruction, threadState.CurrentMethod.Name); } }
public override void Complete(ThreadState threadState) { VMValue_objectinst vinst = (VMValue_objectinst)threadState.GetValue(obj); if(vinst.HoldingLockThreadID == threadState.ThreadID) { vinst.HoldingLockCount--; if(vinst.HoldingLockCount == 0) vinst.HoldingLockThreadID = -1; } else { // If we unlock a lock that // this thread does not possess, the instruction // executes normally but has no effect } if(CheckerConfiguration.DoPrintExecution) { Console.WriteLine("Commiting Unlock in thread " + threadState.CurrentMethod.Name + " on " + obj); } }
public void Close() { lock (LockObject) { if ((_refCount <= 0) || (--_refCount != 0)) { return; } if (Running == ThreadState.Running) { Running = ThreadState.StopRequested; while (Running != ThreadState.Stopped) { Thread.Sleep(1); //todo replace with Task.Delay() when using 4.5 } } _thread = null; if (_ftd2XxHandle != IntPtr.Zero) { FTD2XX.FT_Close(_ftd2XxHandle); _ftd2XxHandle = IntPtr.Zero; } _data = null; } }
internal void MarkForFullFlush() { DocumentsWriterDeleteQueue flushingQueue; lock (this) { if (Debugging.AssertsEnabled) { Debugging.Assert(!fullFlush, "called DWFC#markForFullFlush() while full flush is still running"); Debugging.Assert(fullFlushBuffer.Count == 0, "full flush buffer should be empty: {0}", fullFlushBuffer); } fullFlush = true; flushingQueue = documentsWriter.deleteQueue; // Set a new delete queue - all subsequent DWPT will use this queue until // we do another full flush DocumentsWriterDeleteQueue newQueue = new DocumentsWriterDeleteQueue(flushingQueue.generation + 1); documentsWriter.deleteQueue = newQueue; } int limit = perThreadPool.NumThreadStatesActive; for (int i = 0; i < limit; i++) { ThreadState next = perThreadPool.GetThreadState(i); next.@Lock(); try { if (!next.IsInitialized) { if (closed && next.IsActive) { DocumentsWriterPerThreadPool.DeactivateThreadState(next); // LUCENENET specific - made method static per CA1822 } continue; } if (Debugging.AssertsEnabled) { Debugging.Assert(next.dwpt.deleteQueue == flushingQueue || next.dwpt.deleteQueue == documentsWriter.deleteQueue, " flushingQueue: {0} currentqueue: {1} perThread queue: {2} numDocsInRam: {3}", flushingQueue, documentsWriter.deleteQueue, next.dwpt.deleteQueue, next.dwpt.NumDocsInRAM); } if (next.dwpt.deleteQueue != flushingQueue) { // this one is already a new DWPT continue; } AddFlushableState(next); } finally { next.Unlock(); } } lock (this) { /* make sure we move all DWPT that are where concurrently marked as * pending and moved to blocked are moved over to the flushQueue. There is * a chance that this happens since we marking DWPT for full flush without * blocking indexing.*/ PruneBlockedQueue(flushingQueue); if (Debugging.AssertsEnabled) { Debugging.Assert(AssertBlockedFlushes(documentsWriter.deleteQueue)); } //FlushQueue.AddAll(FullFlushBuffer); foreach (var dwpt in fullFlushBuffer) { flushQueue.Enqueue(dwpt); } fullFlushBuffer.Clear(); UpdateStallState(); } if (Debugging.AssertsEnabled) { Debugging.Assert(AssertActiveDeleteQueue(documentsWriter.deleteQueue)); } }
extern static void SetState(Thread thread, ThreadState set);
public void updateSPCDisplay(object sender, EventArgs e) { ThreadState currentState = searchThread.ThreadState; /* the ugly truth is that the threadState can change during the following * conditions. To avoid problems we set up a local variable first. */ iterationBox.Text = SearchIO.getIteration(searchThread.Name).ToString(); miscBox.Text = SearchIO.getMiscObject(searchThread.Name); verbosityComboBox.SelectedIndex = SearchIO.getVerbosity(searchThread.Name); processTimer.Interval = getIntervalFromVerbosity(); try { priorityComboBox.SelectedIndex = (int)searchThread.Priority; } catch { } if ((currentState == ThreadState.AbortRequested) || (currentState == ThreadState.StopRequested) || (currentState == ThreadState.SuspendRequested)) { this.playButton.Enabled = false; this.pauseButton.Enabled = false; this.stopButton.Enabled = false; this.abortButton.Enabled = true; this.ControlBox = false; this.priorityComboBox.Enabled = true; this.verbosityComboBox.Enabled = true; updateTimeDisplay(); } else if (currentState == ThreadState.Suspended) { this.playButton.Enabled = true; this.pauseButton.Enabled = false; this.stopButton.Enabled = false; this.abortButton.Enabled = true; this.ControlBox = false; this.priorityComboBox.Enabled = true; this.verbosityComboBox.Enabled = true; } else if ((currentState == ThreadState.Running) || (currentState == ThreadState.WaitSleepJoin)) { this.playButton.Enabled = false; this.pauseButton.Enabled = true; this.stopButton.Enabled = true; this.abortButton.Enabled = true; this.ControlBox = false; this.priorityComboBox.Enabled = true; this.verbosityComboBox.Enabled = true; updateTimeDisplay(); } else if ((currentState == ThreadState.Stopped) || (currentState == ThreadState.Aborted)) { if (abortedTime != 0) { long test = DateTime.Now.Ticks - abortedTime; if (test > 50000000) /* after 5 seconds(?) close the search process window */ { this.processTimer.Stop(); this.Close(); } } else { this.playButton.Enabled = false; this.pauseButton.Enabled = false; this.stopButton.Enabled = false; this.abortButton.Enabled = false; this.ControlBox = true; this.priorityComboBox.Enabled = false; this.verbosityComboBox.Enabled = false; abortedTime = DateTime.Now.Ticks; } } }
private bool GetThreadStateBit(ThreadState bit) { Debug.Assert((bit & ThreadState.Stopped) == 0, "ThreadState.Stopped bit may be stale; use GetThreadState instead."); return((_threadState & (int)bit) != 0); }
/// <inheritdoc /> public Possible <ObjectContext, Failure> GetCompletions(ThreadState threadState, int frameIndex, string expr) { return(new Failure <string>("hi")); }
public static void OnStop() { threadState = ThreadState.Stopping; }
extern private static void ClrState (InternalThread thread, ThreadState clr);
public void StopMonitoring() { //_monitoring = false; if( _currentMonitor != null ) { _currentMonitor.Executing = false; _currentMonitor = null; } }
private void ChangeThreadState(ThreadState newState, bool scroll = true) { if (scroll && Version >= WorldModelVersion.v540 && (newState == ThreadState.Ready || newState == ThreadState.Waiting)) { ScrollToEnd(); } if (newState == ThreadState.Waiting && m_state == GameState.Finished) throw new Exception("Game is finished"); m_threadState = newState; lock (m_threadLock) { Monitor.PulseAll(m_threadLock); } }
static void fun1() { ThreadWorkItem itemMain = new ThreadWorkItem { //线程0,1持续运行,设置true后非阻塞,持续运行。需要手动触发Reset()才会阻塞实例所在当前线程 ManualResetEvent = new ManualResetEvent(true), }; //线程工作集合 Task.Factory.StartNew(() => { Thread t = null; ThreadWorkItem item = null; for (int i = 0; i < 2; i++) { t = new Thread((o) => { var w = o as ThreadWorkItem; if (w == null) { return; } while (true) { //阻塞当前线程 bool t = w.ManualResetEvent.WaitOne(10000); Console.WriteLine("我是线程:" + Thread.CurrentThread.Name + ":群里无聊吗?" + !t); if (!t) { break; } Thread.Sleep(200); } Console.WriteLine("我是线程:" + Thread.CurrentThread.Name + "退出了群聊"); }); t.Name = "Hello,i 'am Thread: " + i; item = new ThreadWorkItem { //线程0,1持续运行,设置true后非阻塞,持续运行。需要手动触发Reset()才会阻塞实例所在当前线程 ManualResetEvent = new ManualResetEvent(true), Thread = t, ThreadManagerId = t.ManagedThreadId, ThreadName = t.Name }; Works.Add(item); t.Start(item); } //5秒后准备暂停一个线程1。线程0持续运行 Thread.Sleep(1000); Console.WriteLine("close..."); Works[1].ManualResetEvent.Reset(); //5秒后恢复线程1;线程0,1持续运行 Thread.Sleep(1000); Console.WriteLine("open..."); Works[1].ManualResetEvent.Set(); //5秒后准备暂停一个线程0。线程1持续运行 Thread.Sleep(1000); Console.WriteLine("close0..."); Works[0].ManualResetEvent.Reset(); //5秒后恢复线程1;线程0,1持续运行 Thread.Sleep(1000); Console.WriteLine("open0..."); Works[0].ManualResetEvent.Set(); //5秒后恢复线程1;线程0,1持续运行 Thread.Sleep(5000); Console.WriteLine("closeAll..."); Works[0].ManualResetEvent.Reset(); Works[1].ManualResetEvent.Reset(); while (true) { ThreadState ts = Thread.CurrentThread.ThreadState; Console.WriteLine("我是线程:" + Thread.CurrentThread.Name + "群主解散了群聊"); //while (true) //{ // Thread.CurrentThread.TrySetApartmentState(System.Threading.ThreadState.WaitSleepJoin); // } Thread.CurrentThread.Interrupt(); itemMain.ManualResetEvent.WaitOne(); Thread.Sleep(2000); //Reset(); } }); /// <summary> /// 假设的网络请求 /// </summary> /// <param name="state">参数</param> }
private void ProcessEvent(_PRF.ProfilerSession ps, _PRF.ProfilerEvent pe) { switch (pe.Type) { case _PRF.ProfilerEvent.EventType.Call: { _PRF.FunctionCall f = (_PRF.FunctionCall)pe; m_currentThread = f.m_thread; ThreadState ts; if (m_htThreads.ContainsKey(m_currentThread)) { ts = m_htThreads[m_currentThread]; } else { ts = new ThreadState(); ts.m_threadID = f.m_thread; m_htThreads[f.m_thread] = ts; } Call c = new Call(); c.Function = f.m_callStack[f.m_callStack.Length - 1]; try { m_sess.m_engine.GetMethodName(c.Function, true); } catch { } ts.m_call.AddChild(c); ts.m_call = c; break; } case _PRF.ProfilerEvent.EventType.Return: { _PRF.FunctionReturn f = (_PRF.FunctionReturn)pe; ThreadState ts; if (m_htThreads.ContainsKey(m_currentThread)) { ts = m_htThreads[m_currentThread]; } else { ts = new ThreadState(); ts.m_threadID = f.m_thread; m_htThreads[f.m_thread] = ts; } if ((f.duration & 0x80000000) == 0) { //OffView really really doesn't like negative times. ts.m_call.Duration += f.duration; } if (ts.m_call.Parent != null) { //Make timing inclusive. ts.m_call.Parent.Duration += ts.m_call.Duration; } ts.m_call = ts.m_call.Parent; break; } case _PRF.ProfilerEvent.EventType.ContextSwitch: { _PRF.ContextSwitch c = (_PRF.ContextSwitch)pe; m_currentThread = c.m_thread; break; } } }
/// <summary> /// Marks the most ram consuming active <see cref="DocumentsWriterPerThread"/> flush /// pending /// </summary> protected virtual void MarkLargestWriterPending(DocumentsWriterFlushControl control, ThreadState perThreadState, long currentBytesPerThread) { control.SetFlushPending(FindLargestNonPendingWriter(control, perThreadState)); }
private void PutThreadToWait(HThread Thread, ThreadState State, int TimeoutMs = -1) { SchedulerThread SchedThread; lock (SchedLock) { if (!AllThreads.TryGetValue(Thread, out SchedThread)) { return; } if (SchedThread.Signaled && SchedThread.State == ThreadState.WaitingSignal) { SchedThread.Signaled = false; return; } ActiveProcessors.Remove(Thread.ProcessorId); SchedThread.State = State; TryRunningWaitingThead(SchedThread.Thread.ProcessorId); if (State == ThreadState.WaitingSignal) { InsertSorted(SchedThread); } else { InsertAtEnd(SchedThread); } } if (TimeoutMs >= 0) { Logging.Debug($"{GetDbgThreadInfo(SchedThread.Thread)} waiting with timeout of {TimeoutMs}ms."); SchedThread.WaitEvent.WaitOne(TimeoutMs); } else { Logging.Debug($"{GetDbgThreadInfo(SchedThread.Thread)} waiting indefinitely."); SchedThread.WaitEvent.WaitOne(); } while (true) { lock (SchedLock) { Logging.Debug($"Trying to run {GetDbgThreadInfo(SchedThread.Thread)}."); if (!ActiveProcessors.Contains(SchedThread.Thread.ProcessorId)) { SetThreadAsRunning(SchedThread); break; } else { SchedThread.State = ThreadState.WaitingToRun; Logging.Debug($"{GetDbgThreadInfo(SchedThread.Thread)} waiting to run."); } } SchedThread.WaitEvent.WaitOne(); } }
private static void PrintThreadState(ThreadState state) { Console.WriteLine("{0,-16} : {1}", state, (int)state); }
public static void OnStart() { threadState = ThreadState.Running; }
private static extern void ClrState(Thread thread, ThreadState clr);
public override void OnMessage(string message, EChatEntryType type) { if (message == "LIST" && Bot.MySteamID.Contains(OtherSID.ToString())) { List <long> contextId = new List <long>(); contextId.Add(2); Bot.mySteamInventory.load(Bot.BotGameUsage, contextId, Bot.SteamClient.SteamID); SendChatMessage("My inventory (" + Bot.BotGameUsage + ") contain " + Bot.mySteamInventory.items.Count + " item(s) !"); foreach (KeyValuePair <ulong, GenericInventory.Item> item in Bot.mySteamInventory.items) { SteamTrade.GenericInventory.ItemDescription description = Bot.mySteamInventory.getDescription(item.Key); SendChatMessage(description.name + " in game " + Bot.mySteamInventory.items[item.Key].appid); } } else if (message == "TCP" && Bot.MySteamID.Contains(OtherSID.ToString())) { ThreadState state = Bot.StartListening.ThreadState; SendChatMessage(state.ToString()); } else if (message.StartsWith("EXEC") && Bot.MySteamID.Contains(OtherSID.ToString())) { message = message.Replace("EXEC", ""); string[] cmd = message.Split(' '); if (cmd.Length >= 2) { string command = ""; for (int i = 2; i < cmd.Length; i++) { command += cmd[i] + " "; } command.Remove(command.Length - 1); if (Bot.SendCommandToServer(Int32.Parse(cmd[1]), command)) { SendChatMessage("Executed '" + command + "' on server id '" + cmd[1] + "' !"); } else { SendChatMessage("Wrong server ID, use 'SERVERLIST' to get the server ID."); } } else { SendChatMessage("Usage : EXEC [serverid] [command]"); SendChatMessage("Exemple : EXEC 0 sm_test 1 2 3"); } } else if (message == "SERVERLIST" && Bot.MySteamID.Contains(OtherSID.ToString())) { List <string> existingServer = new List <string>(); SendChatMessage("Number of connection : " + Bot.socket.Clients.Count); SendChatMessage("Server ID Server name"); for (int i = 0; i < Bot.socket.Clients.Count; i++) { if (!existingServer.Contains(Bot.socket.Clients[i].Name) && Bot.socket.Clients[i].clientSocket.Connected) { SendChatMessage(i + " " + Bot.socket.Clients[i].Name); existingServer.Add(Bot.socket.Clients[i].Name); } } SendChatMessage("-----------------------"); } else { SendChatMessage(Bot.chatbotSession.Think(message)); } }
extern static void ClrState(Thread thread, ThreadState clr);
private static extern void SetState(Thread thread, ThreadState set);
/// <summary> /// Gets the list of threads with the given thread-state /// </summary> /// <param name="status"></param> /// <returns>Dataset with thread info.</returns> public ThreadStorageView[] GetThreadList(ThreadState status) { return(ManagerStorageFactory.ManagerStorage().GetThreads(_Id, status)); }
public void SetAllThreadsDebugState(ThreadState state, IDebuggerThread thread) => debugger.Dispatcher.UI(() => DnAppDomain.CorAppDomain.SetAllThreadsDebugState((dndbg.COM.CorDebug.CorDebugThreadState)state, thread == null ? null : ((DebuggerThread)thread).DnThread.CorThread));
extern private static void SetState(InternalThread thread, ThreadState set);
public string Main(string[] args) { ////Set Current Dir in UserProfile //string currDir = SetAppCurrentDir(nameCurrentDir); try { TestInputArgs(args); } catch (ArgumentException argEx) { Console.WriteLine(argEx.Message); //Console.WriteLine("\nPress any Key to Exit!\n"); //Console.ReadKey(); // return; //Directory. appDom = AppDomain.CurrentDomain; Console.WriteLine("\nappDom.BaseDirectory: <{0}>\nappDom.FriendlyName: <{1}>\n", appDom.BaseDirectory, appDom.FriendlyName); Console.WriteLine("\nPress any Key to Exit!\n"); //Console.ReadKey(); return(argEx.Message); } ////Console.WriteLine("\nPress any Key to Exit!\n"); ////Console.ReadKey(); ////return; ////==== //1) Create StreamReader strReader = File.OpenText(inputFile); //for Scanner only USING inputFileEncoding = strReader.CurrentEncoding; Console.WriteLine("\ninputFile: {0} ; File Encoding: {1}", inputFile, inputFileEncoding); //// //AppDomain BaseDirectory AppDomain appDom1 = AppDomain.CurrentDomain; Console.WriteLine("\nappDom.BaseDirectory: <{0}>\nappDom.FriendlyName: <{1}>\n", appDom1.BaseDirectory, appDom1.FriendlyName); ///// //2)Create StreamWriter // //(a)Create one Dir for StreamWriter of Lexer,Scaner and Parser Outputs (after Analisis: options for debugging) // and Parser Output as AST Value after Context Analisis with Diagnostics //(b)Create one Dir for each Expressions: // Private Partition,Polish,Diagramm,Automaton(not built up yet!)(after Good Context Diagnostics :options) // //(b==>c)Create one Dir for each Expressions( 0<=i<=n-1): // (i) Private Partition,Polish,Diagramm,Automaton(not built up yet!) // (i) Public Partition, Representation of Private on Public,Diagram on Public, Automaton in Public(after Good Context Diagnostics :options) // //(d)Create one Dir for Public Partition,Cartesian Product,Classification States and Transitiona(RESULT) // this.nameScaneLexParseDir = currDir + "/" + nameScaneLexParseDir; if (!Directory.Exists(this.nameScaneLexParseDir)) { Directory.CreateDirectory(nameScaneLexParseDir); } //Program.nameScaneLexParseDir Exists! string fileParserOutput = (this.nameScaneLexParseDir + "\\") + outputFile; File.Delete(fileParserOutput); //relative(to the current working directory) or absolute path strWriter = File.CreateText(fileParserOutput); //for Parser only USING Console.WriteLine("\nNew currDirect: {0}\n", currDir); Console.WriteLine("\nfileParserOutput: {0}\n", fileParserOutput); Console.WriteLine("\nPress any Key to Exit!\n"); //Console.ReadKey(); ////return; //3)Create tokenStringQueue and terminalTokenStringQueue tokenStringQueue = new Queue <string>(len_tokenStringQueue); terminalTokenStringQueue = new Queue <string>(len_terminalTokenStringQueue); //4)Create thrScanner Scanner scanner = new Scanner(nameScaneLexParseDir, this.strReader, this.tokenStringQueue); ThreadStart delegateStartScanner = new ThreadStart(scanner.Scane); Thread thrScanner = new Thread(delegateStartScanner); //5)Create thrLexer // Lexer lexer = new Lexer(nameScaneLexParseDir, tokenStringQueue, terminalTokenStringQueue); ThreadStart delegateStartLexer = new ThreadStart(lexer.methodLexem); //Instance Caller method //// ThreadStart delegateStartLexer = new ThreadStart(Lexer.Lexem); //Static method Thread thrLexer = new Thread(delegateStartLexer); //6)Create thrParser Parser parser = new Parser(this.strWriter, this.terminalTokenStringQueue); ThreadStart delegateStartParser = new ThreadStart(parser.Parse); ////Parser.TestParse Thread thrParser = new Thread(delegateStartParser); ThreadState thrScannerState = thrScanner.ThreadState; //eventScanner = new ManualResetEvent(false); ////Scanner.autoResetEvent = new AutoResetEvent(false); if (thrScannerState == ThreadState.Unstarted) { thrScanner.Start(); Console.WriteLine("\nThread Scanner has just started!\n"); } ////ControlThreadScane(thrScanner); thrLexer.Start(); Console.WriteLine("\nThread Lexer has just started!\n"); thrParser.Start(); Console.WriteLine("\nThread Parser has just started!\n"); thrScanner.Join(); Console.WriteLine("\nThread Scanner has just ended!\n"); thrLexer.Join(); Console.WriteLine("\nThread Lexer has just ended!\n"); thrParser.Join(); Console.WriteLine("\nThread Parser has just ended!\n"); strReader.Close(); //after Scanner Return strWriter.Close(); //after Parser Return; //1) - 6) Front End of Compiler //bool isLeftDerive = true; //Derive.TestDerivator(isLeftDerive, Parser.RootAST, "Derivation.txt"); // //7)Back End of Compiler int res = EvaluateAST_Verify_GetAutomataInBasicPartition_CartesianProduct(valueASTFile); //===Public Automata from Diagramms are ready if Verification is succeded! // // //**(8)**Test for <Equals_Id1_Id2>: Boath <Private Partitions> and <Regular Expressions> are different, //but they are in the public alphabet!!! // //TODO: 0)Implement Writing File of Automation with its Private(Public too) Alphabet Partition (Modify old Writing); // 1)Implement Loading up Automation with its Private Alphabet Partition (without Verification)(Modify old Writing); // 2)And Implement Equals for Two Automata with their Private Alphabet Partitions but // before that converting them into Public Alphabet Partition; // Note: Think of '-' (minus symbol in <patterns> at Writing and Reading file)!!! // if (res > 0) { Console.WriteLine("\nres: ({0})\n", res); Console.WriteLine("\nPress any Key to Exit!\n"); //Console.ReadKey(); return(res.ToString()); } goto labelNoEquals; string nameRegularExp_1 = "Identifier"; string fileNameAutomatonFromDiagrammPublic1 = (nameRegularExp_1 + "\\") + (nameRegularExp_1 + "_Private_Automaton.txt"); string fileAut1 = (currDir + "\\") + fileNameAutomatonFromDiagrammPublic1; TestLoadingAutomataAndEquals(fileAut1, fileAut1); string nameRegularExp_2 = "AOctodecimal"; string fileNameAutomatonFromDiagrammPublic2 = (nameRegularExp_2 + "\\") + (nameRegularExp_2 + "_Private_Automaton.txt"); string fileAut2 = (currDir + "\\") + fileNameAutomatonFromDiagrammPublic2; TestLoadingAutomataAndEquals(fileAut1, fileAut2); labelNoEquals: Console.WriteLine("\nres: ({0})\n", res); Console.WriteLine("\nPress any Key to Exit!\n"); //Console.ReadKey(); return(res.ToString()); }
extern private static void ClrState(InternalThread thread, ThreadState clr);
/// <summary> /// Returns the current most RAM consuming non-pending <see cref="ThreadState"/> with /// at least one indexed document. /// <para/> /// This method will never return <c>null</c> /// </summary> protected virtual ThreadState FindLargestNonPendingWriter(DocumentsWriterFlushControl control, ThreadState perThreadState) { Debug.Assert(perThreadState.dwpt.NumDocsInRAM > 0); long maxRamSoFar = perThreadState.bytesUsed; // the dwpt which needs to be flushed eventually ThreadState maxRamUsingThreadState = perThreadState; Debug.Assert(!perThreadState.flushPending, "DWPT should have flushed"); IEnumerator <ThreadState> activePerThreadsIterator = control.AllActiveThreadStates(); while (activePerThreadsIterator.MoveNext()) { ThreadState next = activePerThreadsIterator.Current; if (!next.flushPending) { long nextRam = next.bytesUsed; if (nextRam > maxRamSoFar && next.dwpt.NumDocsInRAM > 0) { maxRamSoFar = nextRam; maxRamUsingThreadState = next; } } } Debug.Assert(AssertMessage("set largest ram consuming thread pending on lower watermark")); return(maxRamUsingThreadState); }
public ThreadProperties(DbgAppDomain appDomain, string kind, ulong id, ulong?managedId, string name, int suspendedCount, ThreadState threadState) { AppDomain = appDomain; Kind = kind; Id = id; ManagedId = managedId; Name = name; SuspendedCount = suspendedCount; ThreadState = threadState; }
/// <summary> /// Gets the count threads with the given thread-state. /// </summary> /// <param name="ts"></param> /// <returns>Thread count</returns> public int ThreadCount(ThreadState ts) { return(ManagerStorageFactory.ManagerStorage().GetApplicationThreadCount(_Id, ts)); }
private bool IsDead() { // Refresh ThreadState.Stopped bit if necessary ThreadState state = GetThreadState(); return (state & (ThreadState.Stopped | ThreadState.Aborted)) != 0; }
/// <summary> /// end this thread /// </summary> public void EndExecution() { this.IsRunning = false; this.IsDoneExecuting = true; this.State = ThreadState.Done; }
public static ThreadState SimpleThreadState(ThreadState ts) { return(ts & (ThreadState.Aborted | ThreadState.AbortRequested | ThreadState.Stopped | ThreadState.Unstarted | ThreadState.WaitSleepJoin)); }
private void LaunchProcess() { try { const string clientExePath = "Client.exe"; ProcessStartInfo info = new ProcessStartInfo(clientExePath); info.UseShellExecute = false; //info.WorkingDirectory = @"C:\Program Files\VTank\"; Process process = Process.Start(info); //bool finished = false; long elapsed = 0; long lastTime = (long)(DateTime.Now - DateTime.FromBinary(0)).TotalMilliseconds;; const long MAX_WAIT_TIME = 15000; while (GetActiveWindowTitle() != "VTank") //&& !finished) Might want this at some point { try { /*int moduleCount = process.Modules.Count; if (!(moduleCount >= 4 && process.Responding)) {*/ long currentTime = (long)(DateTime.Now - DateTime.FromBinary(0)).TotalMilliseconds; elapsed += currentTime - lastTime; lastTime = currentTime; if (elapsed > MAX_WAIT_TIME) break; /*} else { finished = true; }*/ } catch { } finally { Thread.Sleep(25); } } State = ThreadState.SUCCESSFUL; } catch (Exception ex) { Console.Error.WriteLine(ex); failureReason = ex.Message; State = ThreadState.FAILED; } Invoke(new Finished(OnFinish)); }
public void RequestInterrupt() { ThreadState.RequestInterrupt(); }
extern private static void SetState (InternalThread thread, ThreadState set);
static void PrintState(ThreadState state) { Console.WriteLine($"{state,-16} : {(int)state}"); }
private static void ClrState (InternalThread thread, ThreadState clr) { throw new System.NotImplementedException(); }
/// <summary> /// Gets the children. /// </summary> /// <param name="entry">The entry.</param> /// <param name="useCache">if set to <c>true</c> [use cache].</param> /// <param name="receiver">The receiver.</param> /// <returns></returns> public FileEntry[] GetChildren(FileEntry entry, bool useCache, IListingReceiver receiver) { // first thing we do is check the cache, and if we already have a recent // enough children list, we just return that. if (useCache && !entry.NeedFetch) { return(entry.Children.ToArray()); } // if there's no receiver, then this is a synchronous call, and we // return the result of ls if (receiver == null) { DoLS(entry); return(entry.Children.ToArray()); } // this is a asynchronous call. // we launch a thread that will do ls and give the listing // to the receiver Thread t = new Thread(new ParameterizedThreadStart(delegate(object stateData) { ThreadState state = stateData as ThreadState; DoLS(entry); receiver.SetChildren(state.Entry, state.Entry.Children.ToArray()); FileEntry[] children = state.Entry.Children.ToArray(); if (children.Length > 0 && children[0].IsApplicationPackage) { Dictionary <string, FileEntry> map = new Dictionary <string, FileEntry>(); foreach (FileEntry child in children) { string path = child.FullPath; map.Add(path, child); } // call pm. string command = PM_FULL_LISTING; try { this.Device.ExecuteShellCommand(command, new PackageManagerListingReceiver(map, receiver)); } catch (IOException e) { // adb failed somehow, we do nothing. Log.E("FileListingService", e); } } // if another thread is pending, launch it lock (Threads) { // first remove ourselves from the list Threads.Remove(state.Thread); // then launch the next one if applicable. if (Threads.Count > 0) { Thread ct = Threads[0]; ct.Start(new ThreadState { Thread = ct, Entry = entry }); } } })) { Name = "ls " + entry.FullPath }; // we don't want to run multiple ls on the device at the same time, so we // store the thread in a list and launch it only if there's no other thread running. // the thread will launch the next one once it's done. lock (Threads) { // add to the list Threads.Add(t); // if it's the only one, launch it. if (Threads.Count == 1) { t.Start(new ThreadState { Thread = t }); } } // and we return null. return(null); }