public override string GetPropParamFormHtml(HttpRequest request, string param) { int timeLimit = 24; ThreadStatus stickType = ThreadStatus.Sticky; string forumIDs = string.Empty; string unit = "h"; if (string.IsNullOrEmpty(param) == false) { StringList paramList = StringList.Parse(param); timeLimit = int.Parse(paramList[0]); stickType = StringUtil.TryParse <ThreadStatus>(paramList[1]); forumIDs = paramList[2]; unit = paramList[3]; } return(string.Format(@" <p>道具作用时间:<input type=""text"" class=""text number"" name=""prop_TimeLimit"" value=""{0}""/><select name=""prop_timeunit""><option value=""d""" + (unit == "d" ? " selected=\"selected\"" : "") + ">天</option><option value=\"h\"" + (unit == "h" ? " selected=\"selected\"" : "") + ">小时</option><option value=\"m\"" + (unit == "m" ? " selected=\"selected\"" : "") + @">分钟</option></select></p> <p>置顶类型:<label><input type=""radio"" name=""prop_StickType"" value=""1"" {1}/> 板块置顶</label> <label><input type=""radio"" name=""prop_StickType"" value=""2"" {2}/> 全站置顶</label></p> <p>道具有效范围:</p> {3}" , timeLimit , stickType == ThreadStatus.Sticky ? "checked = \"checked\"" : "" , stickType == ThreadStatus.GlobalSticky ? "checked = \"checked\"" : "" , GetFormTreeHtml("prop_formids", forumIDs))); }
public LuaState(GlobalState g) { API = (ILuaAPI)this; NumNonYieldable = 1; NumCSharpCalls = 0; Hook = null; HookMask = 0; BaseHookCount = 0; AllowHook = true; ResetHookCount(); Status = ThreadStatus.LUA_OK; if (g == null) { G = new GlobalState(this); InitRegistry(); } else { G = g; } OpenUpval = new LinkedList <LuaUpvalue>(); ErrFunc = 0; #if DEBUG_RECORD_INS InstructionHistory = new Queue <Instruction>(); #endif InitStack(); }
private static int PCallContinuation(ILuaState lua) { int context; ThreadStatus status = lua.GetContext(out context); return(FinishPCall(lua, status == ThreadStatus.LUA_YIELD)); }
public ThreadStatus L_LoadFileX(string filename, string mode) { ThreadStatus status = ThreadStatus.LUA_OK; if (filename == null) { // 暂不实现从 stdin 输入 throw new System.NotImplementedException(); } int fnameindex = API.GetTop() + 1; API.PushString("@" + filename); try { using (FileLoadInfo loadinfo = LuaFile.OpenFile(filename)) { loadinfo.SkipComment(); status = API.Load(loadinfo, API.ToString(-1), mode); } } catch (LuaRuntimeException e) { API.PushString(string.Format("cannot open {0}: {1}", filename, e.Message)); return(ThreadStatus.LUA_ERRFILE); } API.Remove(fnameindex); return(status); }
/// <summary> /// Função que inicializa as operações da thread. Quando o contrutor EasyThread(EasyThreadFun, bool, object) é utilizado, esta função é executada automaticamente. /// </summary> /// <param name="fun">Função a ser executada</param> /// <param name="runAsWhileTrue">Indica se a thread deve chamar a função "fun" em um "while true". Caso seja true, a função é executada repetidamente.</param> /// <param name="thParams">Parametros que serão passados para a função "fun"</param> public void Start(EasyThreadFun fun, bool runAsWhileTrue, object thParams = null) { if (this.canRun()) { thread = new Thread(delegate() { this.__status = ThreadStatus.running; if (runAsWhileTrue) { while (this.canRun()) { if (!__pause) { fun(this, thParams); } else { this.sleep(1); } } this.__status = ThreadStatus.exited; } else { fun(this, thParams); this.__status = ThreadStatus.exited; } }); thread.Start(); } }
public void Stop() { CheckThreadState(); _threadStatus = ThreadStatus.Stopped; _dataAvailable.Set(); _workerThread = null; }
/// <summary> /// 주어진 매개 변수에 따라 스레드를 시작 /// </summary> /// <param name="opCode">The operation code for creating thread.</param> /// <param name="stackSize">The stack size for the thread.</param> /// <returns>true, if succeeded, otherwise false.</returns> public bool Start(ThreadOpCode opCode = ThreadOpCode.CREATE_START, int stackSize = 0) { lock (m_threadLock) { m_parentThreadHandle = Thread.CurrentThread; if (m_status == ThreadStatus.TERMINATED && m_threadHandle == null) { m_threadHandle = new Thread(ThreadEx.EntryPoint, stackSize); if (m_threadHandle != null) { m_threadHandle.Priority = m_threadPriority; if (opCode == ThreadOpCode.CREATE_START) { m_threadHandle.Start(this); m_status = ThreadStatus.STARTED; } else { m_status = ThreadStatus.SUSPENDED; } return(true); } } // System::OutputDebugString(_T("The thread (%x): Thread already exists!\r\n"),m_threadId); return(false); } }
public async void Generate() { currentStatus = ThreadStatus.Running; while (true) { if (!isActive || isFinished) { if (currentStatus == ThreadStatus.Pausing) { await self.OnTaskDidPaused(); } break; } #if (PROFILING_ENABLED) DateTime start = DateTime.UtcNow; #endif List <TexeraTuple> outputList = new List <TexeraTuple>(); await GenerateTuples(outputList); #if (PROFILING_ENABLED) processTime += DateTime.UtcNow - start; start = DateTime.UtcNow; #endif await MakePayloadMessagesThenSend(outputList); #if (PROFILING_ENABLED) sendingTime += DateTime.UtcNow - start; #endif } }
public void Awake() { Console.WriteLine("LuaScriptController Awake"); if (Lua == null) { Lua = LuaAPI.NewState(); Lua.L_OpenLibs(); ThreadStatus status = Lua.L_DoFile(LuaScriptFile); if (status != ThreadStatus.LUA_OK) { throw new Exception(Lua.ToString(-1)); } if (!Lua.IsTable(-1)) { throw new Exception( "framework main's return value is not a table"); } AwakeRef = StoreMethod("awake"); StartRef = StoreMethod("start"); UpdateRef = StoreMethod("update"); LateUpdateRef = StoreMethod("late_update"); FixedUpdateRef = StoreMethod("fixed_update"); Lua.Pop(1); Console.WriteLine("Lua Init Done"); } CallMethod(AwakeRef); }
public void RequestStop() { if (CurrentStatus == ThreadStatus.Stopped) { return; } int attempt; Logger.Log("RequestStop(): Started.", LogEntryType.Information); _requestedStatus = ThreadStatusRequests.Stop; attempt = 1; while (CurrentStatus != ThreadStatus.Stopped) { if (attempt > STOP_ATTEMPTS) { break; } Thread.Sleep(SLEEP_MS); Logger.Log(String.Format("RequestStop(): Waiting for CurrentStatus to switch to Stopped. Attempt {0}.", attempt), LogEntryType.Information); attempt++; } CurrentStatus = ThreadStatus.Stopped; _workThread = null; Logger.Log("RequestStop(): Finished.", LogEntryType.Information); }
/// <summary> /// Handle non-reply chunks /// </summary> private void ChunkHandler(Chunk chunk) { DLog.Debug(DContext.DebuggerLibDebugger, "Handle Chunk {0}", chunk); var type = chunk.Type; if (type == DdmsCommandSet.HeloType) { var data = chunk.Data; var clientProtocolVersion = data.GetInt(); var pid = data.GetInt(); var vmIdentLen = data.GetInt(); var appNameLen = data.GetInt(); var vmIdent = data.GetString(vmIdentLen); var appName = data.GetString(appNameLen); SetAppName(appName); } else if (type == DdmsCommandSet.ApnmType) { var data = chunk.Data; var appNameLen = data.GetInt(); var appName = data.GetString(appNameLen); SetAppName(appName); } else if (type == DdmsCommandSet.WaitType) { var data = chunk.Data; var reason = data.GetByte(); OnEventAsync(new WaitForDebugger(reason)); } else if (type == DdmsCommandSet.ThstType) { ThreadStatus.HandleTHST(chunk, OnEventAsync); } }
public ThreadEx(ThreadEx b) { m_threadFunc = b.m_threadFunc; m_threadParameterizedFunc = b.m_threadParameterizedFunc; m_parameter = b.m_parameter; if (m_threadFunc != null || m_parentThreadHandle != null) { m_parentThreadHandle = b.m_parentThreadHandle; m_threadHandle = b.m_threadHandle; m_threadPriority = b.m_threadPriority; m_status = b.m_status; m_exitCode = b.m_exitCode; b.m_parentThreadHandle = null; b.m_threadHandle = null; b.m_status = ThreadStatus.TERMINATED; b.m_exitCode = 0; } else { m_threadHandle = null; m_threadPriority = b.m_threadPriority; m_parentThreadHandle = null; m_exitCode = 0; m_status = ThreadStatus.TERMINATED; } }
private static int AuxResume(ILuaState lua, ILuaState co, int narg) { if (!co.CheckStack(narg)) { lua.PushString("too many arguments to resume"); return(-1); // error flag } if (co.Status == ThreadStatus.LUA_OK && co.GetTop() == 0) { lua.PushString("cannot resume dead coroutine"); return(-1); // error flag } lua.XMove(co, narg); ThreadStatus status = co.Resume(lua, narg); if (status == ThreadStatus.LUA_OK || status == ThreadStatus.LUA_YIELD) { int nres = co.GetTop(); if (!lua.CheckStack(nres + 1)) { co.Pop(nres); // remove results anyway; lua.PushString("too many results to resume"); return(-1); // error flag } co.XMove(lua, nres); // move yielded values return(nres); } else { co.XMove(lua, 1); // move error message return(-1); } }
public virtual Task Pause() { #if (PROFILING_ENABLED) TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); Console.WriteLine(Utils.GetReadableName(self) + " receives the pause message at " + (int)t.TotalSeconds); #endif if (currentStatus == ThreadStatus.Pausing) { return(Task.CompletedTask); } else if (currentStatus == ThreadStatus.Paused || isFinished) { return(OnTaskDidPaused()); } foreach (ISendStrategy strategy in sendStrategies.Values) { strategy.SetPauseFlag(true); } currentStatus = ThreadStatus.Pausing; lock (actionQueue) { if (actionQueue.Count == 0) { OnTaskDidPaused(); } } return(Task.CompletedTask); }
public static ThreadStatusType GetThreadStatusTypeByStatus(ThreadStatus status) { if (status == ThreadStatus.FileCopied || status == ThreadStatus.Success) { return(ThreadStatusType.Success); } if (status == ThreadStatus.Connecting || status == ThreadStatus.CopyingFile || status == ThreadStatus.GettingFilesList || status == ThreadStatus.TryingToCopy || status == ThreadStatus.Stopping) { return(ThreadStatusType.Pending); } if (status == ThreadStatus.Error || status == ThreadStatus.NoConnection || status == ThreadStatus.NoFile || status == ThreadStatus.Stopped) { return(ThreadStatusType.Failed); } return(ThreadStatusType.Unknown); }
private bool StartMachine(Thread thread) { ThreadStatus status = new ThreadStatus(); if (CancellationReceived()) { return(false); } try { TraceFactory.Logger.Debug("{0}: Starting background thread".FormatWith(Machine.Name)); thread.IsBackground = true; thread.Start(status); TraceFactory.Logger.Debug("{0}: Waiting for background thread to complete".FormatWith(Machine.Name)); thread.Join(); TraceFactory.Logger.Debug("{0}: Background thread finished".FormatWith(Machine.Name)); } catch (Exception ex) { TraceFactory.Logger.Debug("{0}: Exception: {1}".FormatWith(Machine.Name, ex.ToString())); status.Success = false; } TraceFactory.Logger.Debug("{0}: Background thread completed status: {1}".FormatWith(Machine.Name, status.Success)); return(status.Success); }
void Awake() { if (_lua == null) { _lua = LuaAPI.NewState(); // создаем _lua.L_OpenLibs(); _lua.L_RequireF("mylib", OpenLib, true); _status = _lua.L_DoFile(LuaScriptFile); // throw new Exception( _lua.ToString(-1) ); if (_status != ThreadStatus.LUA_OK) { Debug.LogError("Error parsing lua code"); } if (!_lua.IsTable(-1)) { throw new Exception("framework main's return value is not a table"); } // _lua.L_LoadFile (LuaScriptFile); mainRef = StoreMethod("main"); // _lua.Resume (null, 0); // _lua.Pop (1); } }
public virtual Task Resume() { if (isFinished) { Console.WriteLine("Info: " + Utils.GetReadableName(self) + " already finished! so Resume won't have any effect."); return(Task.CompletedTask); } if (currentStatus != ThreadStatus.Paused) { Console.WriteLine("ERROR: " + Utils.GetReadableName(self) + " invaild state when resume! state = " + currentStatus.ToString()); return(Task.CompletedTask); } currentStatus = ThreadStatus.Idle; Task.Delay(100).ContinueWith((t) => { foreach (ISendStrategy strategy in sendStrategies.Values) { strategy.SetPauseFlag(false); } }); lock (actionQueue) { if (actionQueue.Count == 0) { Task.Delay(100).ContinueWith((t) => { Task.Run(() => { foreach (ISendStrategy strategy in sendStrategies.Values) { strategy.ResumeSending(); } }); }); } } lock (actionQueue) { if (actionQueue.Count > 0) { currentStatus = ThreadStatus.Running; Task.Run(actionQueue.Peek()); } else if (!isFinished && unFinishedUpstream.Count == 0) { Task.Run(async() => { await MakeLastPayloadMessageThenSend(); }); } } if (producer != null) { if (currentStatus == ThreadStatus.Idle && !isFinished) { Console.WriteLine("Resume: " + Common.Utils.GetReadableName(self) + " restart scanning"); Task.Run(() => Generate()); } } Console.WriteLine("Resumed: " + Utils.GetReadableName(self)); return(Task.CompletedTask); }
public void getStatus(ThreadStatus status) { status.threadId = threadId_; status.sentRows = sentRows_; lock (writeQueue_) status.unsentRows = (writeQueue_.Count - 1) * vectorSize + writeQueue_[writeQueue_.Count - 1][0].rows(); status.sendFailedRows = failedQueue_.Count(); }
public void Stop() { if (IsWorking()) { mFinishedContext = null; mStatus = ThreadStatus.STOP; } }
internal ManagedThread(ThreadType type, ContextCallback callback, object state, ExecutionContext ctx) { m_type = type; m_status = (type == ThreadType.QueuedThread ? ThreadStatus.Queued : ThreadStatus.Unstarted); m_ctxCallback = callback; m_state = state; m_ctx = ctx; }
/** * cb will be called in async-thread * */ public void AsyncStop(Callback cb) { if (IsWorking()) { mFinishedContext = cb; mStatus = ThreadStatus.STOP; } }
public Conveyor(ProcessPacketDelegate processPacketDelegate, object context = null) { _dataAvailable = new ManualResetEventSlim(false); _packetsQueue = new ConcurrentQueue <T>(); _processPacketDelegate = processPacketDelegate ?? throw new ArgumentNullException(nameof(processPacketDelegate)); _threadStatus = ThreadStatus.NotStarted; _context = context; }
public AsyncThread(Callback <AsyncThread> cb, object extraData) { mStatus = ThreadStatus.NONE; mContext = cb; mFinishedContext = null; mThread = new Thread(new ThreadStart(ContextMask)); mExtraData = extraData; }
public AsyncThread(Callback<AsyncThread> cb, object extraData) { mStatus = ThreadStatus.NONE; mContext = cb; mFinishedContext = null; mThread = new Thread(new ThreadStart(ContextMask)); mExtraData = extraData; }
public ThreadMonitorEvent(Thread t, string name, ThreadStatus status, string stackTrace) { _Thread = t; _Name = name; _Status = status; _StackTrace = stackTrace; }
public Task OnTaskDidPaused() { //Console.WriteLine("Info: "+Utils.GetReadableName(self)+" currentEndFlagCount: "+currentEndFlagCount); currentStatus = ThreadStatus.Paused; Console.WriteLine("Paused: " + Utils.GetReadableName(self)); principalGrain.OnWorkerDidPaused(self); return(Task.CompletedTask); }
public static int B_LoadFile(ILuaState lua) { string fname = lua.L_OptString(1, null); string mode = lua.L_OptString(2, null); int env = (!lua.IsNone(3) ? 3 : 0); // `env' index or 0 if no `env' ThreadStatus status = lua.L_LoadFileX(fname, mode); return(LoadAux(lua, status, env)); }
public static string GetThreadStatusString(ThreadStatus status) { return(status switch { ThreadStatus.Working => Vars.CurrentLang.Message_ThreadStatus_Working, ThreadStatus.Standby => Vars.CurrentLang.Message_ThreadStatus_Standby, ThreadStatus.Stopped => Vars.CurrentLang.Message_ThreadStatus_Stopped, ThreadStatus.Error => Vars.CurrentLang.Message_ThreadStatus_Error, _ => Vars.CurrentLang.Message_ThreadStatus_Unknown, });
/// <summary> /// Default Constructor /// </summary> /// <param name="priority">The priority of the thread.</param> public ThreadEx() { m_threadHandle = null; m_parentThreadHandle = null; m_status = ThreadStatus.TERMINATED; m_exitCode = 0; m_threadFunc = null; m_threadParameterizedFunc = null; m_parameter = null; }
public ThreadStatus L_DoFile(string filename) { ThreadStatus status = L_LoadFile(filename); if (status != ThreadStatus.LUA_OK) { return(status); } return(API.PCall(0, LuaDef.LUA_MULTRET, 0)); }
private SyncEngine() { status = "Idle"; this.server = Const<BackupServiceClient>.Instance().get(); String dirPath = conf.targetPath.get(); threadCallback = new ThreadStatus(this.ThreadMonitor); watcher = new FileSystemWatcher(); watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnChanged); watcher.Path = dirPath; // Begin watching. watcher.EnableRaisingEvents = true; //Directory.SetCurrentDirectory(dirPath); vb = new FBVersionBuilder(dirPath); }
/// <summary> /// Resume the suspended thread. /// </summary> /// <returns>true, if succeeded, otherwise false.</returns> public bool Resume() { lock (m_threadLock) { if (m_status == ThreadStatus.SUSPENDED && m_threadHandle != null) { m_threadHandle.Resume(); m_status = ThreadStatus.STARTED; return true; } } // System::OutputDebugString(_T("The thread (%x): Thread must be in suspended state in order to resume!\r\n"),m_threadId); return false; }
/// <summary> /// Suspend the running thread. /// </summary> /// <returns>true, if succeeded, otherwise false.</returns> public bool Suspend() { if(m_status==ThreadStatus.STARTED && m_threadHandle!=null) { lock(m_threadLock) { m_status=ThreadStatus.SUSPENDED; } m_threadHandle.Suspend(); return true; } // System::OutputDebugString(_T("The thread (%x): Thread must be in running state in order to suspend!\r\n"),m_threadId); return false; }
/// <summary> /// Default Constructor /// </summary> /// <param name="priority">The priority of the thread.</param> public ThreadEx() { m_threadHandle=null; m_parentThreadHandle=null; m_status=ThreadStatus.TERMINATED; m_exitCode=0; m_threadFunc = null; m_threadParameterizedFunc = null; m_parameter = null; }
private static int LoadAux( ILuaState lua, ThreadStatus status, int envidx ) { if( status == ThreadStatus.LUA_OK ) { if( envidx != 0 ) // `env' parameter? { lua.PushValue(envidx); // push `env' on stack if( lua.SetUpvalue(-2, 1) == null ) // set `env' as 1st upvalue of loaded function { lua.Pop(1); // remove `env' if not used by previous call } } return 1; } else // error (message is on top of the stack) { lua.PushNil(); lua.Insert(-2); // put before error message return 2; // return nil plus error message } }
public Error GetThreadStatus(out ThreadStatus threadStatus, out SuspendStatus suspendStatus, ThreadId thread) { byte[] packet = new byte[HeaderSize + ThreadIdSize]; int id = GetMessageId(); SerializeHeader(packet, id, ThreadReferenceCommand.Status); WriteObjectId(packet, HeaderSize, thread); byte[] response = SendPacket(id, packet); Error errorCode = ReadErrorCode(response); if (errorCode != Error.None) { threadStatus = default(ThreadStatus); suspendStatus = default(SuspendStatus); return errorCode; } int offset = HeaderSize; threadStatus = (ThreadStatus)ReadInt32(response, ref offset); suspendStatus = (SuspendStatus)ReadInt32(response, ref offset); return Error.None; }
public ThreadObject() { SyncRoot = new object(); m_Thread = Thread.CurrentThread; m_Thread.Name = String.Format("JobWorker {0}", m_NextID++); m_Job = null; m_Status = ThreadStatus.Running; m_Signal = new AutoResetEvent(false); }
/// <summary> /// Starts a separate thread that sends key commands in an attempt to Trade with an NPC ONLY. Keeps attempting for 30 seconds. Does not work well with PC Trade menu!! /// </summary> /// <param name="TargetID">Target ID of the NPC ONLY to trade with.</param> public void OpenTradeMenu(int TargetID) { // If we're already running, we'll cancel running ANOTHER THREAD! if (lastTradeMenuStatus != ThreadStatus.Running) { if ((TargetID <= 0) || (TargetID >= 1024)) { lock (TradeMenuLock) { this._TradeMenuThread = ThreadStatus.Failed; return; } } lock (TradeMenuLock) { this._TradeMenuThread = ThreadStatus.Running; } // Worst case scenario, we check Status and it's reported as "Running" // but was on the last line before Failed/Succeeded. // We still don't want to run another before user gets a chance to verify status. System.Threading.Thread openMenuThread = new System.Threading.Thread(() => OpenTradeMenuThread(TargetID)); openMenuThread.Start(); } }
/// <summary> /// Terminate the thread successfully. /// </summary> private void successTerminate() { lock (m_threadLock) { m_status = ThreadStatus.TERMINATED; m_threadHandle = null; m_parentThreadHandle = null; m_exitCode = 0; } onTerminated(m_exitCode); }
public bool Start() { if (null != mThread) { mStatus = ThreadStatus.START; mThread.Start(); return true; } return false; }
/// <summary> /// Internal function that handled opening the Trade Menu depending on current state. /// </summary> /// <param name="TargetID">ID of NPC to trade with.</param> private void OpenTradeMenuThread(int TargetID) { lock (TradeMenuLock) { this._TradeMenuThread = ThreadStatus.Running; } String TradeMenuSelection = "Trade"; String TradeMenuHelp = ""; String TradeMenuHelpHighlighted = "Trade items or money with current target."; bool TradeMenuOpen = false; bool TargetCorrect = false; bool TradeMenuSelected = false; double DistanceToTarget = 0.0f; double GoodDistance = 4.0f; if ((_FFACE != null) && (TargetID > 0)) { DateTime SequenceStart = DateTime.Now; // Continue looping until both Target is correct and TradeMenu is open, or 30seconds pass... this allows for 15s of running to target as well. // (!TargetCorrect || !TradeMenuOpen) && while ((DateTime.Now - SequenceStart).TotalMilliseconds < 30000) { TargetCorrect = (_FFACE.Target.ID == TargetID); TradeMenuOpen = (_FFACE.Menu.IsOpen && (_FFACE.Menu.Selection == TradeMenuSelection) && (_FFACE.Menu.Help == TradeMenuHelp)); TradeMenuSelected = (_FFACE.Menu.IsOpen && (_FFACE.Menu.Selection == TradeMenuSelection) && (_FFACE.Menu.Help == TradeMenuHelpHighlighted)); DistanceToTarget = _FFACE.Navigator.DistanceTo(TargetID); _FFACE.Navigator.FaceHeading(TargetID); if (!_FFACE.Menu.IsOpen && (DistanceToTarget > GoodDistance) && (DistanceToTarget < 40.0f)) { double store = _FFACE.Navigator.DistanceTolerance; _FFACE.Navigator.DistanceTolerance = GoodDistance; _FFACE.Navigator.GotoNPC(TargetID, 20000); // Restore old DistanceTolerance _FFACE.Navigator.DistanceTolerance = store; } else if (!_FFACE.Menu.IsOpen && !TargetCorrect && (DistanceToTarget <= GoodDistance)) { _FFACE.Windower.SendKeyPress(KeyCode.TabKey); } else if (!_FFACE.Menu.IsOpen && TargetCorrect && (DistanceToTarget <= GoodDistance)) { _FFACE.Windower.SendKeyPress(KeyCode.NP_MinusKey); } else if (_FFACE.Menu.IsOpen && TargetCorrect && (DistanceToTarget <= GoodDistance) && (_FFACE.Menu.Selection != TradeMenuSelection)) { _FFACE.Windower.SendKeyPress(KeyCode.UpArrow); } else if (_FFACE.Menu.IsOpen && TargetCorrect && (DistanceToTarget <= GoodDistance) && TradeMenuSelected) { _FFACE.Windower.SendKeyPress(KeyCode.EnterKey); } else if (_FFACE.Menu.IsOpen && TargetCorrect && (DistanceToTarget <= GoodDistance) && TradeMenuOpen) { // Correct setting lock (TradeMenuLock) { this._TradeMenuThread = ThreadStatus.Succeeded; } return; } // get out of trade menu with wrong person... Esc -> Enter else if (_FFACE.Menu.IsOpen && !TargetCorrect) { _FFACE.Windower.SendKeyPress(KeyCode.EscapeKey); System.Threading.Thread.Sleep(250); if (TradeMenuOpen) { _FFACE.Windower.SendKeyPress(KeyCode.EnterKey); System.Threading.Thread.Sleep(250); } } System.Threading.Thread.Sleep(125); } } lock (TradeMenuLock) { this._TradeMenuThread = ThreadStatus.Failed; } }
/// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected void Dispose(bool disposing) { if (disposing) { lock (this) { _threadStatus = ThreadStatus.Stop; Monitor.PulseAll(this); } foreach (Thread thread in _threadPool) thread.Join(); } }
/// <summary> /// Joins this instance. /// </summary> public void Join() { lock (this) { _threadStatus = ThreadStatus.Join; _joiningThreadPoolCount = _threadPool.Length; Monitor.PulseAll(this); } lock (_joiningObject) { while (_joiningThreadPoolCount > 0) Monitor.Wait(_joiningObject); _threadStatus = ThreadStatus.Idle; } }
private bool Recover( ThreadStatus status ) { CallInfo ci = FindPCall(); if( ci == null ) // no recover point return false; StkId oldTop = Stack[ci.ExtraIndex]; F_Close( oldTop ); SetErrorObj( status, oldTop ); CI = ci; AllowHook = ci.OldAllowHook; NumNonYieldable = 0; ErrFunc = ci.OldErrFunc; ci.CallStatus |= CallStatus.CIST_STAT; ci.Status = status; return true; }
/// <summary> /// Terminate the running or suspended thread. /// </summary> /// <returns>true, if succeeded, otherwise false.</returns> public bool Terminate() { Debug.Assert(m_threadHandle != Thread.CurrentThread, "Exception : Thread should not terminate self."); if (m_status != ThreadStatus.TERMINATED && m_threadHandle != null) { lock (m_threadLock) { m_status = ThreadStatus.TERMINATED; m_exitCode = 1; m_threadHandle.Abort(); m_threadHandle = null; m_parentThreadHandle = null; } ulong exitCode = m_exitCode; onTerminated(exitCode); return true; } return true; }
/// <summary> /// Detach the thread /// </summary> public void Detach() { Debug.Assert(Joinable() == true); lock (m_threadLock) { m_status = ThreadStatus.TERMINATED; m_threadHandle = null; m_parentThreadHandle = null; m_exitCode = 0; } }
/** * This function may cause a little perfermance problem. * */ private void ContextMask() { mStatus = ThreadStatus.WORKING; mContext(this); if (mStatus == ThreadStatus.STOP) { if (null != mFinishedContext) { mFinishedContext(); } mStatus = ThreadStatus.FINISHED; } }
/// <summary> /// Reset Thread /// </summary> private void resetThread() { if(m_status!=ThreadStatus.TERMINATED) { m_exitCode=1; m_threadHandle.Abort(); onTerminated(m_exitCode,true); } m_threadHandle=null; m_parentThreadHandle=null; m_exitCode=0; m_status = ThreadStatus.TERMINATED; }
/// <summary> /// Default Constructor /// </summary> /// <param name="threadParameterizedFunc">the parameterized function for the thread</param> /// <param name="priority">The priority of the thread.</param> public ThreadEx(Action<object> threadParameterizedFunc,object parameter, ThreadPriority priority = ThreadPriority.Normal) { m_threadHandle = null; m_threadPriority = priority; m_parentThreadHandle = null; m_status = ThreadStatus.TERMINATED; m_exitCode = 0; m_threadFunc = null; m_threadParameterizedFunc = threadParameterizedFunc; m_parameter = parameter; m_parentThreadHandle = Thread.CurrentThread; m_threadHandle = new Thread(ThreadEx.entryPoint); m_threadHandle.Priority = m_threadPriority; m_threadHandle.Start(this); m_status = ThreadStatus.STARTED; }
/** * cb will be called in sync-thread * */ public void SyncStop(Callback cb) { if (IsWorking()) { mFinishedContext = null; mStatus = ThreadStatus.STOP; while (mStatus != ThreadStatus.FINISHED) ; cb(); } }
/// <summary> /// Default copy constructor /// </summary> /// <param name="b">the object to copy from</param> public ThreadEx(ThreadEx b) { m_threadFunc=b.m_threadFunc; m_threadParameterizedFunc = b.m_threadParameterizedFunc; m_parameter = b.m_parameter; if(m_threadFunc!=null||m_parentThreadHandle!=null) { m_parentThreadHandle=b.m_parentThreadHandle; m_threadHandle=b.m_threadHandle; m_threadPriority=b.m_threadPriority; m_status=b.m_status; m_exitCode=b.m_exitCode; b.m_parentThreadHandle=null; b.m_threadHandle=null; b.m_status=ThreadStatus.TERMINATED; b.m_exitCode=0; } else { m_threadHandle=null; m_threadPriority=b.m_threadPriority; m_parentThreadHandle=null; m_exitCode=0; m_status = ThreadStatus.TERMINATED; } }
/// <summary> /// Default Constructor /// </summary> /// <param name="threadFunc">the function for the thread</param> /// <param name="priority">The priority of the thread.</param> public ThreadEx(Action threadFunc) { m_threadHandle = null; m_parentThreadHandle = null; m_status = ThreadStatus.TERMINATED; m_exitCode = 0; m_threadFunc = threadFunc; m_threadParameterizedFunc = null; m_parameter = null; m_parentThreadHandle=Thread.CurrentThread; m_threadHandle=new Thread(ThreadEx.entryPoint); m_threadHandle.Start(this); m_status=ThreadStatus.STARTED; }
/// <summary> /// Start the Thread according to parameters given. /// </summary> /// <param name="opCode">The operation code for creating thread.</param> /// <param name="stackSize">The stack size for the thread.</param> /// <returns>true, if succeeded, otherwise false.</returns> public bool Start(ThreadOpCode opCode=ThreadOpCode.CREATE_START, int stackSize=0) { lock(m_threadLock) { m_parentThreadHandle=Thread.CurrentThread; if(m_status==ThreadStatus.TERMINATED&& m_threadHandle==null) { m_threadHandle=new Thread(ThreadEx.entryPoint,stackSize); if (m_threadHandle != null) { m_threadHandle.Priority = m_threadPriority; if (opCode == ThreadOpCode.CREATE_START) { m_threadHandle.Start(this); m_status = ThreadStatus.STARTED; } else m_status = ThreadStatus.SUSPENDED; return true; } } // System::OutputDebugString(_T("The thread (%x): Thread already exists!\r\n"),m_threadId); return false; } }
private static int LoadAux( ILuaState lua, ThreadStatus status ) { if( status == ThreadStatus.LUA_OK ) return 1; else { lua.PushNil(); lua.Insert(-2); // put before error message return 2; // return nil plus error message } }
internal void HandleItem() { // Set start state m_startTime = DateTime.UtcNow.Ticks; m_status = ThreadStatus.Executing; try { // Invoke the user's call back function if (m_ctx == null) { if (m_tsCallback != null) { m_tsCallback.Invoke(); } else if (m_ptsCallback != null) { m_ptsCallback.Invoke(m_state); } else { m_ctxCallback.Invoke(m_state); } } else { // If user specified an alternate execution context, we invoke // their delegate under that context ExecutionContext.Run(m_ctx, m_ctxCallback, m_state); } } finally { // Set finish state if (m_status == ThreadStatus.Executing) { m_status = ThreadStatus.Completed; } m_stopTime = DateTime.UtcNow.Ticks; ManagedThreads.Remove(this); } }
/// <summary> /// Default Constructor /// </summary> /// <param name="priority">The priority of the thread.</param> public ThreadEx(ThreadPriority priority=ThreadPriority.Normal) { m_threadHandle=null; m_threadPriority=priority; m_parentThreadHandle=null; m_status=ThreadStatus.TERMINATED; m_exitCode=0; m_threadFunc = null; m_threadParameterizedFunc = null; m_parameter = null; }