public MainWindow() { InitializeComponent(); // Get the taskbar icon object Tb = this.ProcessNotifyIcon; Tb.ToolTipText = Properties.Resources.ProgramName; // Set window title this.Title = Properties.Resources.ProgramName; // Initial setting CurrentStatus = ProcessStatus.Stopped; UpdateIcon(); // Don't show window SetWindowVisibility(false); // Load the settings LoadSettings(); // Start the checking process StartCheckProcess(); if (ShowBalloonMessageOnStart) { Tb.ShowBalloonTip(Properties.Resources.ProgramName, "Started", BalloonIcon.Info); } }
public ValueVersion(UInt64 ve, string ss, byte[] va, int ec, ProcessStatus status, Int64 start, Int64 stop) { version = ve; shortStatus = ss; value = va; exitCode = ec; startTime = start; stopTime = stop; switch (status) { case ProcessStatus.Queued: processStatus = "Queued"; break; case ProcessStatus.Running: processStatus = "Running"; break; case ProcessStatus.Canceling: processStatus = "Canceling"; break; default: processStatus = "Completed"; break; } }
public ExtendedValidationResult(string errorMessage, ProcessStatus status, object customState) : base(errorMessage) { Status = status; CustomState = customState; }
int VertexCount = 1; // Used to count vertexes. #endregion Fields #region Constructors public LdrawToObj() { // Set default settings. inputFile = outputFile = sourceDir = ""; line = step = stud = hollow = tube = false; skiperror = false; stopConvert = ProcessStatus.NOTSTARTED; }
int updatecounter = 0; // Subpart force update progress #endregion Fields #region Constructors public LdrawToData() { // Set default settings. inputFile = outputFile = sourceDir = ""; line = step = stud = hollow = tube = false; skiperror = false; polylist = new List<PolyShape>(); stopConvert = ProcessStatus.NOTSTARTED; }
public ProcessInfo (DateTime startTime, TimeSpan age, int processID, int requestCount, ProcessStatus status, ProcessShutdownReason shutdownReason, int peakMemoryUsed) { this.age = age; this.peakMemoryUsed = peakMemoryUsed; this.processID = processID; this.requestCount = requestCount; this.shutdownReason = shutdownReason; this.startTime = startTime; this.status = status; }
public void SetAll(DateTime startTime, TimeSpan age, int processID, int requestCount, ProcessStatus status, ProcessShutdownReason shutdownReason, int peakMemoryUsed) { this._StartTime = startTime; this._Age = age; this._ProcessID = processID; this._RequestCount = requestCount; this._Status = status; this._ShutdownReason = shutdownReason; this._PeakMemoryUsed = peakMemoryUsed; }
public void Start() { this.processStatus = ProcessStatus.Running; if (this.IsBusy) { return; } this.intervalManualReset = new ManualResetEvent(false); this.RunWorkerAsync(); }
public void SetProcessStatus(Guid processId, ProcessStatus newStatus) { if (newStatus == ProcessStatus.Running) { SetRunningStatus(processId); } else { SetCustomStatus(processId, newStatus); } }
public Task CollectAsync(IUserNotification notification, string channel, ProcessStatus status, CancellationToken ct = default) { Guard.NotNull(notification); Guard.NotNullOrEmpty(channel); var counterMap = CounterMap.ForChannel(channel, status); var counterKey = CounterKey.ForNotification(notification); return(StoreCountersAsync(counterKey, counterMap, ct)); }
// Always called when process is locked public void Launch(string logDirectory, ProcessStartInfo startInfo) { if (status == ProcessStatus.Completed) { logger.Log("process " + id + " already canceled so not starting"); return; } try { process = new Process(); process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Exited += new EventHandler(OnExited); logger.Log("About to start process " + id); var started = process.Start(); if (started) { logger.Log("Process " + id + " started successfully"); status = ProcessStatus.Running; startTime = process.StartTime.ToFileTimeUtc(); string name = "process-" + id; string stdOutDest = name + "-stdout.txt"; string stdErrDest = name + "-stderr.txt"; if (logDirectory != null) { stdOutDest = Path.Combine(logDirectory, stdOutDest); stdErrDest = Path.Combine(logDirectory, stdErrDest); } else { stdOutDest = Path.Combine(startInfo.WorkingDirectory, stdOutDest); stdErrDest = Path.Combine(startInfo.WorkingDirectory, stdErrDest); } Task copyOutTask = Task.Run(() => CopyStreamWithCatch(process.StandardOutput, stdOutDest)); Task copyErrTask = Task.Run(() => CopyStreamWithCatch(process.StandardError, stdErrDest)); } else { logger.Log("Process " + id + " failed to start"); SetCompletedStatus(); } } catch (Exception e) { logger.Log("Error starting process " + id + ": " + e.ToString()); SetCompletedStatus(); } UnblockMailboxes(); }
/// <summary> /// Starts the remote process which will host an Activator /// </summary> public void Start() { CheckDisposed(); DisposeClient(); Logger.InfoFormat("Starting process for Process Domain '{0}'", _friendlyName); String processGuid = Guid.NewGuid().ToString(); bool created; var serverStartedHandle = new EventWaitHandle(false, EventResetMode.ManualReset, string.Format(ActivatorHost.EventName, processGuid), out created); // We set guid to a new value every time therefore this "should" never happen. if (!created) { throw new Exception("Event handle already existed for remote process"); } string processDomainAssemblyPath = AssemblyUtils.GetFilePathFromFileUri(typeof(ActivatorProcess).Assembly.CodeBase); ProcessDomainSetup.Serialize(_setupInfo, _setupInfoFile); // args[0] = process domain assembly path // args[1] = guid // args[2] = process id // args[3] = ProcessDomainSetup file _process.StartInfo.Arguments = string.Format("\"{0}\" {1} {2} \"{3}\"", processDomainAssemblyPath, processGuid, Process.GetCurrentProcess().Id, _setupInfoFile); if (!_process.Start()) { throw new Exception(string.Format("Failed to start process from: {0}", _process.StartInfo.FileName)); } Logger.InfoFormat("Process successfully started with process id {0}", _process.Id); if (!serverStartedHandle.WaitOne(_setupInfo.ProcessStartTimeout)) { throw new Exception("Timed-out waiting for remote process to start"); } serverStartedHandle.Close(); _processStatus = ProcessStatus.Active; _process.PriorityClass = _setupInfo.PriorityClass; _client = new ActivatorClient(processGuid, _setupInfo); var tmp = Attached; if (tmp != null) { tmp(); } }
/// <summary> /// Retorna o estado do processo de adoção. /// </summary> public static string GetProcessStatusName(this ProcessStatus processStatus) { switch (processStatus) { case ProcessStatus.Finished: return("Concluído"); case ProcessStatus.Cancelled: return("Cancelado"); default: case ProcessStatus.Pending: return("Pendente"); } }
internal virtual ProcessStatus GetCurrentStatus() { if ((_previousStatus != BaseProcess.ProcessStatus.UserActionRequired) && (Status == BaseProcess.ProcessStatus.UserActionRequired)) { SendEmailItem(_BIAdminOncallEmail, "User action required for process " + ProcessName, ""); } //update previous status _previousStatus = Status; return(Status); }
protected override void ChangeStatus(ProcessStatus status) { base.ChangeStatus(status); if (status == ProcessStatus.Running) { Config.Instance.ClientOn = true; } else { Config.Instance.ClientOn = false; } }
public ActionResult SetStatus(ProcessStatus status, string message) { Status = status; if (message != null) { Message = message; } //fluent shmuent return(this); }
/// <summary> /// 从处理状态中获得其字面意思 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetTip(string str) { try { ProcessStatus status = (ProcessStatus)Enum.Parse(typeof(ProcessStatus), str); return(GetTip(status)); } catch { return(string.Empty); } }
public static ProcessInfo GetCurrentProcessInfo() { DateTime startTime = DateTime.Now; TimeSpan age = TimeSpan.Zero; int processID = 0; int requestCount = 0; ProcessStatus status = ProcessStatus.Terminated; ProcessShutdownReason shutdownReason = ProcessShutdownReason.None; int peakMemoryUsed = 0; return(new ProcessInfo(startTime, age, processID, requestCount, status, shutdownReason, peakMemoryUsed)); }
private void SetCustomStatus(Guid processId, ProcessStatus status) { var dbcoll = Store.GetCollection <WorkflowProcessInstanceStatus>(MongoDBConstants.WorkflowProcessInstanceStatusCollectionName); var instanceStatus = dbcoll.FindOneById(processId); if (instanceStatus == null) { throw new StatusNotDefinedException(); } instanceStatus.Status = status.Id; dbcoll.Save(instanceStatus); }
protected override void ChangeStatus(ProcessStatus status) { base.ChangeStatus(status); gbxInfo.IsEnabled = status == ProcessStatus.Running; if (status == ProcessStatus.Running) { Config.Instance.ServerOn = true; } else { Config.Instance.ServerOn = false; } }
private void UpdateBatchStatus(Guid batchId, ProcessStatus status) { var batchTobeUpdated = _dbContext.Batches.Where(batch => batch.Id == batchId).FirstOrDefault(); if (batchTobeUpdated != null) { _dbContext.Batches.Remove(batchTobeUpdated); batchTobeUpdated.Status = status; _dbContext.Batches.Add(batchTobeUpdated); batchTobeUpdated.Jobs.ToList().ForEach(job => UpdateJobStatus(job.Id, status)); } }
public void CanTerminateAProcessStatus() { DateTime started = DateTime.UtcNow.AddSeconds(-10); DateTime ended = DateTime.UtcNow; ProcessStatus status = new ProcessStatus(started); status.Complete(ended, true); Assert.AreEqual(started, status.StartedAt); Assert.IsTrue(status.EndedAt.HasValue); Assert.AreEqual(ended, status.EndedAt.Value); Assert.IsTrue(status.EndedWithError); }
public NotifyController(IBotFrameworkHttpAdapter adapter, IConfiguration configuration, ConcurrentDictionary <string, ConversationReference> conversationReferences, IBot bot, User user) { _adapter = adapter; _appId = configuration["MicrosoftAppId"]; _conversationReferences = conversationReferences; _bot = bot; _user = user; _processStatus = new ProcessStatus(); if (string.IsNullOrEmpty(_appId)) { _appId = Guid.NewGuid().ToString(); } }
private void SetCustomStatus(Guid processId, ProcessStatus status) { using (var session = Store.OpenSession()) { var instanceStatus = session.Load <WorkflowProcessInstanceStatus>(processId); if (instanceStatus == null) { throw new StatusNotDefinedException(); } instanceStatus.Status = status.Id; session.SaveChanges(); } }
/// <summary> /// Removes the specified id. /// </summary> /// <param name="id">The id.</param> public void Remove(string id) { lock (syncRoot) { ProcessStatus.Remove(id); ProcessStatusMessage.Remove(id); string typeFullName = this.GetType().FullName; if (SingleTaskIdByTypeName.Keys.Count(x => x == typeFullName) == 1) { SingleTaskIdByTypeName.Remove(typeFullName); } } }
private void SetCustomStatus(ProcessInstance processInstance, ProcessStatus status, bool createIfnotDefined = false) { var db = _connector.GetDatabase(); var hash = string.Format("{0:N}", processInstance.ProcessId); if (!createIfnotDefined && !db.HashExists(GetKeyProcessStatus(), hash)) { throw new StatusNotDefinedException(); } var batch = db.CreateBatch(); batch.HashDeleteAsync(GetKeyProcessRunning(), hash); batch.HashSetAsync(GetKeyProcessStatus(), hash, status.Id); batch.Execute(); }
/// <summary> /// This method sets up the initial setup for the enemy generation. /// </summary> /// <param name="numberOfEnemies">The number of enemies to generate, /// of type int</param> /// <param name="stage">The stage from which to start to put enemies /// on, of type BouncyStage</param> public void SetupGeneration(int numberOfEnemies, BouncyStage stage) { // Correcting the number of enemies generation // if any errors found _numberOfEnemies = numberOfEnemies >= EnemyMax ? EnemyMax : numberOfEnemies; _currentStage = stage; // Setting the current stage _processCounter = 0; // Resetting the process counter _status = ProcessStatus.Generating; // Starting to add // enemies }
public void onLockTaken(VesselData vd) { Debug.Assert(this.status == ProcessStatus.WAITING_VESSEL, "[SupplyChain] SupplyChainProcess " + this.pid.ToString() + ": onLockTaken called while not waiting on vessel!"); this.status = ProcessStatus.RUNNING; /* Fire next action-- we (must) always pass thru the WAITING_ACTION and WAITING_VESSEL state before beginning to execute an action. */ Debug.Log("[SupplyChainProcess] Process " + pid.ToString() + " has taken lock for vessel " + vd.vessel.name + ", executing action #" + currentIndex.ToString()); if (!sequence[currentIndex].startAction()) { /* Vessel not in correct state anymore-- give up lock and go back to waiting. */ vd.unlockVessel(this); status = ProcessStatus.WAITING_ACTION; } }
public ProcessRecord(int i, ILogger l, Action collect) { logger = l; collector = collect; id = i; status = ProcessStatus.Queued; exitCode = unchecked ((int)Constants.WinError_StillActive); mailbox = new Dictionary <string, MailboxRecord>(); // every process has a record corresponding to the 'null' key that is used for monitoring // the lifetime of the process var record = new MailboxRecord(); mailbox.Add(Constants.NullKeyString, record); }
/// <summary> /// This method loads the game stage. /// </summary> /// <param name="level">The current level of the game, of type /// int</param> /// <param name="levelNumberCurrent">The current stage number /// of the game, of type /// int</param> public void LoadStage(int level, int levelNumberCurrent) { _level = level; // Setting the current level // Setting the current stage number _levelNumberCurrent = levelNumberCurrent; CheckLevel(); // Checking if the level is correct at the start CalculateNumberOfLines(); // Calculating the number of points needed // for line renderer // Starting the generation process Status = ProcessStatus.Generating; }
public async Task ChangeStatusAsync(int processId, ProcessStatus status, string reviewNotes = null) { var process = await this.context.Processes.FirstOrDefaultAsync(p => p.Id == processId); process.Status = status; process.ReviewNotes = null; if (status == ProcessStatus.Approved || status == ProcessStatus.Rejected) { process.ReviewDate = DateTime.Now; process.ReviewNotes = reviewNotes; } await this.context.SaveChangesAsync(); }
static void Main(string[] args) { Console.Title = _APP_NAME; _PROCESS_HWND = Win32.Imports.FindWindowByCaption(IntPtr.Zero, _PROCESS_NAME); _STATUS = _PROCESS_HWND != IntPtr.Zero ? ProcessStatus.Found : ProcessStatus.NotFound; if (_STATUS == ProcessStatus.Found) { Console.WriteLine("Process found. Now initializing..."); // TODO: BACKGROUND THREAD FOR PROCESSING _THREAD = new Thread(BackProcess); _THREAD.IsBackground = true; _THREAD.Start(_THREAD_DELAY_RANGE); // INPUT THREAD while (true) { ConsoleKeyInfo keyInfo = Console.ReadKey(); _MUT.WaitOne(); { switch (keyInfo.Key) { // TODO: make sure that the previous thread hasn't changed anything... appropriately // ie. set to do something else, but then this thread cancels it case ConsoleKey.Escape: _STATUS = ProcessStatus.Terminated; break; default: break; } // do not forget to release the mutex, if breaking out early! if (_STATUS == ProcessStatus.Terminated) { _MUT.ReleaseMutex(); break; } } _MUT.ReleaseMutex(); } } else if (_STATUS == ProcessStatus.NotFound) { Console.WriteLine("Process not found. Hit any key to exit process."); } }
public ServerData() { m_IPAddress = ""; m_port = 0; m_ServerDirectory = "-"; m_LaunchOption = ""; m_PStat = ProcessStatus.Lost; m_NStat = NetworkStatus.Waiting; m_ProcessTryCnt = 0; m_NetworkTryCnt = 0; m_isActive = true; m_rqstInfo = new RQST_INFO(); m_rqstPlayerList = new List <RQST_PLAYER>(); }
public virtual void Fail(string message) { Argument.NotNull(message, "message"); if (Status != ProcessStatus.Pending) { throw new DomainException("Current state is already final."); } if (Type == TransactionType.Withdrawal) { Account.Deposit(-AccountAmount); } RemainingBalance = Account.Balance; ErrorMessage = message; Status = ProcessStatus.Failed; }
public virtual void Complete(DateTime postDateUtc) { Argument.Satisfies(postDateUtc, x => x >= DateTime.UtcNow.Date, "postDateUtc", "Post date should be today or later."); if (Status != ProcessStatus.Pending) { throw new DomainException("Current state is already final."); } if (Type == TransactionType.Deposit) { Account.Deposit(AccountAmount); } RemainingBalance = Account.Balance; PostDateUtc = postDateUtc; Status = ProcessStatus.Completed; }
public void Log(LoggerLevel type, string Message) { if (type == LoggerLevel.CRITICAL_ERROR) { _Status = ProcessStatus.FALIL; } if (_Status != ProcessStatus.FALIL) { _Status = ProcessStatus.SUCCESS; } Writer.Write(type.GetDescription(), Message, _ApplicationName); }
private ProcessStatus CheckPrcessStatus(CheckProcess checkProcess) { var processInfoResult = new ProcessStatus(); var proc = Process.GetProcesses().FirstOrDefault(x => string.Compare(checkProcess.Name, x.ProcessName, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) == 0); processInfoResult.Name = checkProcess.Name; if ((!_watchDogFlags.ContainsKey(checkProcess.Name) || _watchDogFlags[checkProcess.Name] == false) && proc != null) { _logger.Warn($"processController {checkProcess.Name} without WD, need restart app"); } processInfoResult.StatusProcess = proc != null ? ProcessStatus.ProcStatus.Running : ProcessStatus.ProcStatus.NotRunning; return(processInfoResult); }
protected override void CallBackGitProcessExit(object sender, int code) { _objGitMgr._objGitMgrCore.Async_DataReceived_Event -= ProcessReceiveData; _objGitMgr._objGitMgrCore.Async_Exited_Event -= ProcessAbort; _objGitMgr._objGitMgrCore.Async_ErrorReceived_Event -= ProcessErrorData; _bIsRegGitEvent = false; m_barOperProgress.Value = 100; if (code == 0)//successful { _bIsPulled = true; m_txOperRes.ForeColor = Color.Green; m_txOperRes.AppendText("--------- Pull Remote repository to local branch Successfully ---------" + Environment.NewLine); _OperStatus = ProcessStatus.PROCESS_START; m_btnRun.Enabled = true; m_btnCancel.Enabled = true; m_btnStop.Enabled = false; m_checkRebaseMode.Enabled = true; //show which file has been merged ShowSuccessCommitChange(); } else { //can't implement the merge operation, deal with conflict if (_objGitMgr._objGitMgrCore.IsAnyUnMergeFile(_szWorkingdir)) { m_txOperRes.ForeColor = Color.Red; m_txOperRes.AppendText("------------ Pull Remote repository to local branch failed ------------" + Environment.NewLine); ShowConflict(); } else //failed { m_txOperRes.ForeColor = Color.Red; m_txOperRes.AppendText("------------ Pull Remote repository to local branch failed ------------" + Environment.NewLine); _OperStatus = ProcessStatus.PROCESS_START; m_lvConflict.Items.Clear(); m_btnRun.Enabled = true; m_btnCancel.Enabled = true; m_btnStop.Enabled = false; m_checkRebaseMode.Enabled = true; } } }
public void WorkRunner() { try { Status = ProcessStatus.RUNNING; Work(); if (Status == ProcessStatus.RUNNING) Status = ProcessStatus.COMPLETED; } catch (ThreadAbortException) { Status = ProcessStatus.ABORTED; } catch { Status = ProcessStatus.FAILED; } }
/*=====================================Public Function=======================================*/ //開始此節點進程,通常受上一節點呼叫 public void Begin(){ //改變狀態 this.status = ProcessStatus.ACTIVE; //開始每一個事件 foreach (ProcessEvent eachEvent in eventList){ eachEvent.Begin(); } //開始每一個條件檢查 foreach (ProcessCondition eachCondition in conditionToNextList){ eachCondition.Begin(); } //event onProcessBegin(); }
//結束此節點進程 public void End(){ //改變狀態 this.status = ProcessStatus.INACTIVE; //結束每一個事件 foreach (ProcessEvent eachEvent in eventList){ eachEvent.End(); } //結束每一個條件檢查 foreach (ProcessCondition eachCondition in conditionToNextList){ eachCondition.End(); } //event onProcessEnd(); }
/// <summary> /// Cancel process instance /// Cancels all currently active transitions and removes all tokens /// from the process. /// TODO: implement /// </summary> public void CancelProcessInstance() { log.Info("Cancelling process"); lock (this) { foreach (string corrId in _activeTransitions.Keys) { TaskShell ts = GetActiveTransition(corrId); if (ts.Status == TransitionStatus.ENABLED || ts.Status == TransitionStatus.STARTED) { CancelTransition(corrId); } } _currentMarking = new Dictionary<string, int>(); _status = ProcessStatus.Cancelled; FinishDate = DateTime.Now; } log.Info("Process cancelled"); ProcessCancelled pc = new ProcessCancelled(); pc.CorrelationId = this.CorrelationId; pc.DefinitionId = this.ProcessDefinitionId; pc.InstanceId = this.InstanceId; NotifyProcessEvent(pc); }
private void SetProcessStatusInvoke(ProcessStatus s) { _Status=s; if (OnStatusChanged != null) OnStatusChanged(_Status); }
// Always called when process is locked public void Cancel() { if (status == ProcessStatus.Completed) { logger.Log("process " + id + " already canceled so not killing"); return; } if (status == ProcessStatus.Running) { try { logger.Log("trying to kill process " + id); process.Kill(); } catch (Exception e) { logger.Log("error killing process " + id + ": " + e.ToString()); } status = ProcessStatus.Canceling; // wait for the event telling us the process has exited before unblocking the waiters return; } logger.Log("setting queued process " + id + " to completed"); exitCode = unchecked((int)Constants.DrError_VertexReceivedTermination); SetCompletedStatus(); UnblockMailboxes(); }
private void SetCompletedStatus() { status = ProcessStatus.Completed; stopTime = process.ExitTime.ToFileTimeUtc(); // after 30 seconds, call our parent to garbage collect the record and its mailboxes Task.Delay(30 * 1000).ContinueWith((t) => collector()); }
void setup() { Timer = new Timer(TimeSpan.FromSeconds((double) TimingData.Interval).TotalMilliseconds); Timer.AutoReset = true; Timer.Enabled = true; Timer.Elapsed += new ElapsedEventHandler(TimerInterval); Process = new Process(); Process.StartInfo.FileName = executable; Process.StartInfo.Arguments = parameters; Process.EnableRaisingEvents = true; Process.Exited += new EventHandler(ProcessExited); InternalStatus = ProcessStatus.INACTIVE; RestartTimer = new System.Threading.Timer((Object _) => { if (InternalStatus != ProcessStatus.INACTIVE) Start(); }); QueryRestorationTimer = new System.Threading.Timer((Object _) => { runqueries = true; }); // Queries if (Query == QueryType.SOURCE) { SourceQuery = new SourceQuery(this); } }
void ProcessStartupThread() { try { bool res = true; if (Process.MainWindowHandle != IntPtr.Zero) res = Process.WaitForInputIdle((int) TimeSpan.FromSeconds((double) TimingData.Startup).TotalMilliseconds); lock (ProcLock) { if (!ProcRunning()) { Stop(); return; } if (res) { strikes = 0; //LastStartup = DateTime.Now; InternalStatus = ProcessStatus.RUNNING; SendProcUpdate(); // Get an immediate ping // TimerInterval(null, null); PushInfo("Started up"); } else { ++strikes; if (strikes > 3) { Stop(); PushInfo("Failed to start up in time 3 times in a row."); } else { Process.Kill(); PushInfo("Failed to start up in time."); } } } } catch (Exception e) { PushError("Could not start up", e.Message); Stop(); } }
void ProcessExited(Object proc, EventArgs args) { lock (ProcLock) { if (InternalStatus != ProcessStatus.INACTIVE) { // Force a delay between restarts InternalStatus = ProcessStatus.STARTING; SendProcUpdate(); /* // Slow down crash loops TimeSpan LongEnough = TimeSpan.FromMinutes(5); if (DateTime.Now.Subtract(LastStartup) > LongEnough) { RestartDelay = TimeSpan.FromSeconds(1); } else { RestartDelay += TimeSpan.FromSeconds(1); } */ // Retrigger the timer RestartTimer.Change(RestartDelay, TimeSpan.FromMilliseconds(-1)); } else { Stop(); } } }
public void Stop() { lock (ProcLock) { Timer.Stop(); bool shutdown = ProcRunning(); InternalStatus = ProcessStatus.INACTIVE; SendPingUpdate(-2); SendProcUpdate(); if (shutdown) { if (Process.Responding) { // If the process is running normally, politely ask it to shut down Process.CloseMainWindow(); // Then make sure it actually closes var t = new System.Threading.Thread(ProcessKillThread); t.IsBackground = true; t.Start(); } } } }
// Talky things public void Start() { lock (ProcLock) { try { if (ProcRunning()) Process.Kill(); Process.Start(); if (Affinity != IntPtr.Zero) Process.ProcessorAffinity = Affinity; Timer.Start(); InternalStatus = ProcessStatus.STARTING; SendProcUpdate(); strikes = 0; var t = new System.Threading.Thread(ProcessStartupThread); t.IsBackground = true; t.Start(); } catch (Exception e) { PushError("Could not start up", e.Message); Stop(); } } }
/// <summary> /// executes one or more process steps /// returns true - if process could continue /// returns false - if process cannot continue /// </summary> /// <returns></returns> public bool Kick() { bool b = KickTokens(); if (Status == ProcessStatus.Ready || Status == ProcessStatus.Waiting) { _status = b ? ProcessStatus.Ready : ProcessStatus.Waiting; } return Status == ProcessStatus.Ready; }
private void SetIconStatus(ProcessStatus ps) { switch (ps) { case ProcessStatus.ProgramPaused: Tb.Icon = Properties.Resources.ProcessPaused; break; case ProcessStatus.Stopped: Tb.Icon = Properties.Resources.ProcessStopped; break; case ProcessStatus.Checking: Tb.Icon = Properties.Resources.ProcessChecking; break; case ProcessStatus.Running: Tb.Icon = Properties.Resources.ProcessRunning; break; default: Tb.Icon = Properties.Resources.ProcessStopped; break; } }
private void SetProcessStatus(ProcessStatus ps) { CurrentStatus = ps; UpdateIcon(); }
public ServerProcessUpdateEventArgs(Int32 PID, ProcessStatus stat) { Status = stat; ProcessID = PID; }
public ProcessRecord(int i, ILogger l, Action collect) { logger = l; collector = collect; id = i; status = ProcessStatus.Queued; exitCode = unchecked((int)Constants.WinError_StillActive); mailbox = new Dictionary<string, MailboxRecord>(); // every process has a record corresponding to the 'null' key that is used for monitoring // the lifetime of the process var record = new MailboxRecord(); mailbox.Add(Constants.NullKeyString, record); }
/// <summary> /// Add new token to process instance /// </summary> /// <param name="tok"></param> public void CreateStartToken() { if (!_activated) throw new Exception("Process instance not activated"); lock (this) { AddToken(Definition.Start.Id); _status = ProcessStatus.Ready; if (GetNumFreeTokens(Definition.Start.Id) == 1) { OnProcessStarted(); } } }
// Always called when process is locked public void Launch(string logDirectory, ProcessStartInfo startInfo) { if (status == ProcessStatus.Completed) { logger.Log("process " + id + " already canceled so not starting"); return; } try { process = new Process(); process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Exited += new EventHandler(OnExited); logger.Log("About to start process " + id); var started = process.Start(); if (started) { logger.Log("Process " + id + " started successfully"); status = ProcessStatus.Running; startTime = process.StartTime.ToFileTimeUtc(); string name = "process-" + id; string stdOutDest = name + "-stdout.txt"; string stdErrDest = name + "-stderr.txt"; if (logDirectory != null) { stdOutDest = Path.Combine(logDirectory, stdOutDest); stdErrDest = Path.Combine(logDirectory, stdErrDest); } else { stdOutDest = Path.Combine(startInfo.WorkingDirectory, stdOutDest); stdErrDest = Path.Combine(startInfo.WorkingDirectory, stdErrDest); } Task copyOutTask = Task.Run(() => CopyStreamWithCatch(process.StandardOutput, stdOutDest)); Task copyErrTask = Task.Run(() => CopyStreamWithCatch(process.StandardError, stdErrDest)); } else { logger.Log("Process " + id + " failed to start"); SetCompletedStatus(); } } catch (Exception e) { logger.Log("Error starting process " + id + ": " + e.ToString()); SetCompletedStatus(); } UnblockMailboxes(); }
// Methods public void SetAll(System.DateTime startTime, System.TimeSpan age, int processID, int requestCount, ProcessStatus status, ProcessShutdownReason shutdownReason, int peakMemoryUsed) {}
/// <summary> /// Restore process state from a DataObject (obtained by calling SaveProcessState). /// This is the preferred way of storing process state in NGinn. Of course /// process instance can be binary serialized and saved, but the binary format /// causes problems when upgrading class versions. /// </summary> /// <param name="dob"></param> public void RestoreState(DataObject dob) { if (this._activated) throw new ApplicationException("Restore is not possible after activation"); string v = (string) dob["APIVersion"]; if (!APIVERSION.Equals(v)) { log.Warn("Trying to restore process state from version {0}. API version is {1}", v, APIVERSION); } DateTime dt = DateTime.MinValue; _instId = (string) dob["InstanceId"]; _definitionId = (string) dob["ProcessDefinitionId"]; _status = (ProcessStatus)Enum.Parse(typeof(ProcessStatus), (string) dob["Status"]); _persistedVersion = Convert.ToInt32(dob["PersistedVersion"]); _startedBy = (string)dob["StartedBy"]; dob.TryGet("StartDate", ref _startDate); if (dob.TryGet("FinishDate", ref dt)) FinishDate = dt; DataObject vars = (DataObject)dob["InstanceData"]; _processInstanceData = new DataObject(); _processInstanceData["variables"] = vars; _correlationId = (string)dob["CorrelationId"]; _transitionNumber = Convert.ToInt32(dob["TransitionNumber"]); _currentMarking = new Dictionary<string, int>(); IList l = dob.GetArray("Marking"); if (l != null) { foreach (DataObject d2 in l) { string plid = (string)d2["Place"]; int n = Convert.ToInt32(d2["Tokens"]); _currentMarking[plid] = n; } } _activeTransitions = new Dictionary<string, TaskShell>(); IList l2 = dob.GetArray("Transition"); if (l2 != null) { foreach (DataObject dob2 in l2) { TaskShell ts = TaskShell.RestoreTaskShell(dob2); _activeTransitions[ts.CorrelationId] = ts; } } }
public ProcessInstance() { _status = ProcessStatus.Ready; }