public void SetWorkerStatus(IWorker worker, WorkerStatus workerStatus) { if (!_workers.Contains(worker)) { _workers.Add(worker); } }
/// <summary> /// This method handles the life-cycle management of the thread, as some /// marketing people would put it. /// </summary> private void InternalRun() { Debug.Assert(Status == WorkerStatus.Running); try { Run(); } catch (WorkerCancellationException) { Status = WorkerStatus.Cancelled; } catch (Exception e) { Status = WorkerStatus.Failed; FailException = e; } if (Status == WorkerStatus.Running) { Status = WorkerStatus.Success; } Base.ExecInUI(new Base.EmptyDelegate(InternalOnCompletion)); }
private void doWork() { HttpServer sv = this.Server; try { sv.LOG_DEBUG("Start worker#{0}", this.WorkerNumber); while (!sv.m_stoprequest) { this.WorkerEvent.WaitOne(); if (sv.m_stoprequest) { break; } this.Status = WorkerStatus.BUSY; sv.OnConnect(this); this.Status = WorkerStatus.WAITING; } sv.LOG_DEBUG("Stop worker#{0}", this.WorkerNumber); } catch (ThreadAbortException) { // OnConnect内でログを吐いているので、ここでは何もしなくてよい } catch (Exception ex) { sv.LOG_ERR("Worker#{0} caught exception {1}", this.WorkerNumber, ex.GetType().Name); sv.LOG_EXCEPTION(ex); } finally { this.Status = WorkerStatus.STOPPED; } }
public void SetStatus(WorkerStatus status, string reason) { if (status != this.Status) { Debug.Log(string.Format("#{0}. Changing status from {1} to {2}. Reason: {3}", this.ID, this.Status, status, reason)); } this.Status = status; switch (status) { case WorkerStatus.Free: //Graphics.renderer.material.color = Color.gray; break; case WorkerStatus.Active: //Graphics.renderer.material.color = Color.yellow; break; case WorkerStatus.Travelling: //Graphics.renderer.material.color = Color.green; break; case WorkerStatus.Working: //Graphics.renderer.material.color = Color.red; break; default: break; } }
// =============== // internal methods void contextTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (GetStatus() == WorkerStatus.Running) { if (firstRunningTime == DateTime.MinValue) { firstRunningTime = DateTime.Now; } TimeSpan runTime = DateTime.Now - firstRunningTime; if (DateTime.Now >= stopTime) { myStatus = WorkerStatus.Completed; WorkerCompleteEvent(myRequest); } else if (DateTime.Now >= timeoutTime) { myStatus = WorkerStatus.Timeout; WorkerCompleteEvent("failed <" + myRequest + "> timeout"); } else if (DateTime.Now >= updateTime) { updateTime = updateTime.AddMilliseconds(updateIncrement); WorkerUpdateEvent("*"); } } }
public PrintSort() // needs to be public for an external user to instantiate { myRequest = null; myResult = null; myStatus = WorkerStatus.Init; firstRunningTime = DateTime.MinValue; }
public void FreeTool() { this.Tools["right"].Status = ToolStatus.FREE; this.Tools["left"].Status = ToolStatus.FREE; this.leftNeigbhor.Tools["right"] = this.Tools["left"]; this.Tools["left"] = null; }
public async Task ProcessThresholdsExceeded_OutOfProc_ReturnsExpectedResult(ProcessStats hostProcessStats, List <ProcessStats> allWorkerProcessStats, bool expected) { var workerStatuses = new Dictionary <string, WorkerStatus>(); foreach (var workerProcessStats in allWorkerProcessStats) { var workerStatus = new WorkerStatus { ProcessStats = workerProcessStats }; workerStatuses.Add(Guid.NewGuid().ToString(), workerStatus); } var mockDispatcher = new Mock <IFunctionInvocationDispatcher>(MockBehavior.Strict); mockDispatcher.SetupGet(p => p.State).Returns(FunctionInvocationDispatcherState.Initialized); mockDispatcher.Setup(p => p.GetWorkerStatusesAsync()).ReturnsAsync(workerStatuses); var mockDispatcherFactory = new Mock <IFunctionInvocationDispatcherFactory>(MockBehavior.Strict); mockDispatcherFactory.Setup(p => p.GetFunctionDispatcher()).Returns(mockDispatcher.Object); var mockScriptHostManager = new Mock <IScriptHostManager>(MockBehavior.Strict); var scriptHostManagerServiceProviderMock = mockScriptHostManager.As <IServiceProvider>(); scriptHostManagerServiceProviderMock.Setup(p => p.GetService(typeof(IFunctionInvocationDispatcherFactory))).Returns(mockDispatcherFactory.Object); _serviceProviderMock.Setup(p => p.GetService(typeof(IScriptHostManager))).Returns(mockScriptHostManager.Object); _mockProcessMonitor.Setup(p => p.GetStats()).Returns(hostProcessStats); Collection <string> exceededCounters = new Collection <string>(); bool result = await _performanceManager.ProcessThresholdsExceeded(exceededCounters, _logger); Assert.Equal(expected, result); }
public void UnsafeAbort() { if (_status == WorkerStatus.Closed) { return; } lock (_locker) { if (_thread != null) { if (Thread.VolatileRead(ref _abortWait) > 0) { if (_status < WorkerStatus.NotifyAbort) { _status = WorkerStatus.NotifyAbort; } return; } _thread.Abort(); _thread = null; } close(); } }
public void UpdateStatus(WorkerStatus newStatus, uint jobsCompleted) { _nodeStatus.Status = newStatus; _nodeStatus.JobsCompleted = jobsCompleted; SendStatusUpdate(); }
/// <summary> /// Sets this worker's status. /// </summary> /// <param name="status">The status to set.</param> internal void SetStatus(WorkerStatus status) { using (IRepository repository = this.repositoryFactory.Create()) { this.SetStatus(status, repository, null); } }
public bool Stop(int timeout) { Process worker = _worker; if (worker == null) { return(true); } _worker = null; _status = WorkerStatus.Stopped; WriteCommand(ConsoleCommand.StopCommand); if (worker.Id == Process.GetCurrentProcess().Id) { return(true); } try { if (!worker.WaitForExit(timeout)) { worker.Kill(); worker.WaitForExit(); } worker.Dispose(); } catch (Exception ex) { Trace.WriteLine(ex); } return(true); }
public void UpdateStatus(WorkerStatus newStatus, uint jobsCompleted) { _nodeStatus.Status = newStatus; _nodeStatus.JobsCompleted = jobsCompleted; SendStatusUpdate(); }
private void checkButton_Click(object sender, RoutedEventArgs e) { switch (Status) { case WorkerStatus.Idle: Globals.LogInfo(Components.ProxyManager, "Disabling the UI and starting the checker"); checkButton.Content = "ABORT"; botsSlider.IsEnabled = false; Status = WorkerStatus.Running; #pragma warning disable CS4014 // Non è possibile attendere la chiamata, pertanto l'esecuzione del metodo corrente continuerà prima del completamento della chiamata CheckProxiesAsync(vm.ProxyList, vm.BotsNumber, 200); #pragma warning restore CS4014 // Non è possibile attendere la chiamata, pertanto l'esecuzione del metodo corrente continuerà prima del completamento della chiamata break; case WorkerStatus.Running: Globals.LogWarning(Components.ProxyManager, "Abort signal sent"); checkButton.Content = "HARD ABORT"; Status = WorkerStatus.Stopping; cts.Cancel(); break; case WorkerStatus.Stopping: Globals.LogWarning(Components.ProxyManager, "Hard abort signal sent"); checkButton.Content = "CHECK"; botsSlider.IsEnabled = true; Status = WorkerStatus.Idle; break; } }
public WorkerState(string name, string type, WorkerStatus status, DateTime?busySince) { Name = name; Type = type; Status = status; BusySince = busySince; }
public Worker(string name, WorkerStatus workerStatus) { this.Name = name; this.status = workerStatus; this.Tools.Add("right", null); this.Tools.Add("left", null); }
/// <summary> /// 启动工作线程 /// </summary> /// <returns>是否成功</returns> public virtual ARESULT Start() { lock (mLock) { if (mStatus == WorkerStatus.Running) { return(ARESULT.E_ALREADY_EXISTS); } else if (mStatus != WorkerStatus.Idle) { return(ARESULT.E_FAIL); } mStatus = WorkerStatus.Running; mRunFlag = true; try { if (!ThreadPool.QueueUserWorkItem(Execute)) { mStatus = WorkerStatus.Idle; mRunFlag = false; return(ARESULT.E_FAIL); } } catch { mStatus = WorkerStatus.Idle; mRunFlag = false; return(ARESULT.E_FAIL); } } return(ARESULT.S_OK); }
/// <summary> /// 等待工作线程结束 /// </summary> public virtual void Join() { lock (mLock) { if (mStatus == WorkerStatus.Idle) { return; } mStatus = WorkerStatus.WaitFor; mWaitCount++; } lock (mEvent) { Monitor.Wait(mEvent); } lock (mLock) { if (--mWaitCount > 0) { return; } mStatus = WorkerStatus.Idle; } }
/// <summary> /// Cancels the worker execution when it's work is done. /// </summary> public void Cancel() { if (_status == WorkerStatus.Working) { _status = WorkerStatus.Canceled; } }
static int OldMain(string[] args) { // the job of this process is to: // instantiate a worker // intantiate a connection to the queues // listen for incoming messages // process them // testing instantiates a worker locally and exercises it through the IWorker interface // to ensure a) the worker works, and b) wrapper process logic works bool testing = true; if (testing) { TestMe(); return(0); } Init(args[0].Split('|')); if (myWorker == null || thisExch == null || !thisExch.IsOpen) { return(0); } myStatus = WorkerStatus.Running; contextTimer.Enabled = true; while (myStatus != WorkerStatus.Shutdown) { System.Threading.Thread.Sleep(sleepIncrement); } return(1); }
public async Task <WorkerStatus> GetWorkerStatusAsync() { var workerStatus = new WorkerStatus(); if (!string.IsNullOrEmpty(_workerCapabilities.GetCapabilityState(RpcWorkerConstants.WorkerStatus))) { // get the worker's current status // this will include the OOP worker's channel latency in the request, which can be used upstream // to make scale decisions var message = new StreamingMessage { RequestId = Guid.NewGuid().ToString(), WorkerStatusRequest = new WorkerStatusRequest() }; var sw = ValueStopwatch.StartNew(); var tcs = new TaskCompletionSource <bool>(); if (_workerStatusRequests.TryAdd(message.RequestId, tcs)) { SendStreamingMessage(message); await tcs.Task; var elapsed = sw.GetElapsedTime(); workerStatus.Latency = elapsed; _workerChannelLogger.LogDebug($"[HostMonitor] Worker status request took {elapsed.TotalMilliseconds}ms"); } } workerStatus.IsReady = IsChannelReadyForInvocations(); if (_environment.IsWorkerDynamicConcurrencyEnabled()) { workerStatus.LatencyHistory = GetLatencies(); } return(workerStatus); }
/// <summary> /// Processor /// </summary> /// <returns></returns> private async Task ProcessAsync() { try { Status = WorkerStatus.ProcessingJob; _outer.OnJobStarted?.Invoke(this, new JobInfoEventArgs(Job)); // Start sending heartbeats _heartbeatTimer.Change(TimeSpan.FromSeconds(1), _outer._heartbeatInterval); await _currentProcessingEngine.RunAsync(_currentJobProcessInstruction.ProcessMode.Value, _cancellationTokenSource.Token); _cancellationTokenSource.Token.ThrowIfCancellationRequested(); _logger.Information("Job {job} completed.", Job.Id); } catch (OperationCanceledException) { _logger.Information("Job {job} cancelled.", Job.Id); } catch (Exception ex) { _logger.Error(ex, "Error processing job {job}.", Job.Id); kModuleExceptions.WithLabels("", ex.Source, ex.GetType().FullName, ex.Message, ex.StackTrace, "Error processing job " + Job.Id).Inc(); Job.LifetimeData.Status = JobStatus.Error; } finally { // Stop sending heartbeats _heartbeatTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); await CleanupAsync(); } }
internal bool Run(string magicCookie) { if (string.IsNullOrEmpty(magicCookie)) { Log("ipc not available");// EventLogEntryType.Error, 1000); return(false); } if (_component != null) { Log("worker already initialized");//, EventLogEntryType.Error, 1000); return(false); } //object obj = null; //try //{ // obj = Activator.CreateInstance(Type.GetType(Configuration.Component, true)); //} //catch (Exception ex) //{ // Log("failed to create " + Configuration.Component + ":\r\n" + ex, EventLogEntryType.Error, 1000); // return false; //} //if (obj == null) //{ // Log("failed to create " + Configuration.Component, EventLogEntryType.Error, 1000); // return false; //} _component = new EggComponent(); //obj as IHAComponent; _waitForExit = new ManualResetEvent(false); if (_runAsConsole) { MasterConsole master = new MasterConsole(magicCookie); master.Worker = System.Diagnostics.Process.GetCurrentProcess(); Thread t = new Thread(RunAsConsoleApp); t.IsBackground = true; t.Name = "HA_Worker_Runas_Console_App"; t.Start(master); } _console = new WorkerConsole(magicCookie); _console.PingCommandReceived += OnPingCommandReceived; _console.StartCommandReceived += OnStartCommandReceived; _console.PauseCommandReceived += OnPauseCommandReceived; _console.ResumeCommandReceived += OnResumeCommandReceived; _console.StopCommandReceived += OnStopCommandReceived; _status = WorkerStatus.Ready; _console.Initialized(); _waitForExit.WaitOne(); return(true); }
protected override void OnStopping() { // Engine is down if (this.Status == WorkerStatus.Down) { return; } // Engine is sutting down, or is starting wait a little bit until is finalize its transitioning. if (this.Status == WorkerStatus.ShuttingDown) { Thread.Sleep(100); this.OnStopping(); } // This means that the System is up and running. Can safely stop if (this.Status == WorkerStatus.UpAndRunning || this.Status == WorkerStatus.Starting) { this.Status = WorkerStatus.ShuttingDown; this.bus.Publish(new StopEventProcessor(), new StopEventPublisher(), new StopEventPoller()); this.Status = WorkerStatus.Down; this.OnStopping(); } }
public bool Start(int timeout) { if (_worker == null) { return(false); } if (!_workerInitialize.WaitOne(timeout)) { return(false); } _status = WorkerStatus.Ready; if (!WriteCommand(ConsoleCommand.StartCommand)) { return(false); } if (ConsoleCommandEvent.WaitAny(_startResponse, timeout) != ConsoleCommand.StartSuccess) { return(false); } _status = WorkerStatus.Running; return(true); }
/// <summary> /// Starts engine /// </summary> public new void Start() { if (systemHaltRequested) { this.OnSystemHalt(); } // Is started if (this.Status == WorkerStatus.UpAndRunning) { return; } if (this.Status == WorkerStatus.Down) { this.Status = WorkerStatus.Starting; base.Start(); // Check if is started to release thread. this.Start(); } if (this.Status == WorkerStatus.Starting || this.Status == WorkerStatus.ShuttingDown) { Thread.Sleep(100); this.Start(); } }
public void Pause() { if (status == WorkerStatus.Running || status == WorkerStatus.Queued) { timer.Stop(); status = WorkerStatus.Paused; if (smRespStream != null) { smRespStream.Close(); } if (saveFileStream != null) { saveFileStream.Close(); } if (unpackProcess != null && !unpackProcess.HasExited) { unpackProcess.Kill(); } lvi.SubItems[1].Text = "Pausado"; } //progress.Value = 0; }
public void Cancel() { timer.Stop(); if (status == WorkerStatus.Completed) { return; } status = WorkerStatus.Canceled; if (smRespStream != null) { smRespStream.Close(); } if (saveFileStream != null) { saveFileStream.Close(); } if (unpackProcess != null && !unpackProcess.HasExited) { unpackProcess.Kill(); } lvi.SubItems[1].Text = ""; lvi.SubItems[2].Text = "Cancelado"; progressValue = 0; progress.Value = progressValue; DeletePkg(); }
public static string GetWorkerStatusDesc(WorkerStatus status) { string _desc; switch (status) { case WorkerStatus.aid: _desc = "На больничном"; break; case WorkerStatus.dismissed: _desc = "Уволен"; break; case WorkerStatus.onHoliday: _desc = "В отпуске"; break; case WorkerStatus.working: _desc = "На работе"; break; default: _desc = "не известно"; break; } return(_desc); }
public Worker(string workerId, WorkerStatus workerStatus, object result, object command, bool storeCommands) { WorkerStatus = workerStatus; Result = result; Command = command; WorkerId = workerId; StoreCommands = storeCommands; }
internal Worker(Action action, bool isPeriodical) { _action = action; if (isPeriodical) { _status = WorkerStatus.Periodical; } }
public void Colorlize(Rectangle rec, WorkerStatus status) { switch (status) { case WorkerStatus.Idle: rec.Fill = Brushes.Silver; break; case WorkerStatus.Busy: rec.Fill = Brushes.YellowGreen; break; } }
public void GiveTask(WorkerTask task) { _targetReached = false; if (_task) _task.SetInUse(false); if (task) { _task = task; GoToTarget(); } else { _task = null; _status = WorkerStatus.Idle; } }
public static void Log(string message, string type, string username, string context, string header) { using (var db = new MySelfieEntities()) { var entity = new WorkerStatus(); entity.Message = message; entity.TimeStamp = DateTime.UtcNow; entity.Type = type; entity.UserName = username; entity.Context = context; entity.Status = "new"; entity.Header = header; db.WorkerStatus.Add(entity); db.SaveChanges(); } }
/// <summary> /// This method handles the life-cycle management of the thread, as some /// marketing people would put it. /// </summary> private void InternalRun() { Debug.Assert(Status == WorkerStatus.Running); try { Run(); } catch (KWorkerCancellationException) { Status = WorkerStatus.Cancelled; } catch (Exception e) { Status = WorkerStatus.Failed; FailException = e; } if (Status == WorkerStatus.Running) Status = WorkerStatus.Success; KBase.ExecInUI(new KBase.EmptyDelegate(InternalOnCompletion)); }
public void Reset() { if (!IsBusy) { AsynchOp = null; IsAsynch = false; WorkerStatus = WorkerStatus.Uninitialized; PercentProgress = 0; CompletionCalled = false; SettingsPersister.Reset(); } else { // TODO log this???? throw new InvalidOperationException("Reset()"); } }
public LogViewModel(WorkerStatus entity) { this.MergeWithOtherType(entity); this.Id = entity.WorkerStatusID; this.Source = "Scraper"; }
public void UnpersistElement(System.Xml.XmlReader reader) { IsAsynch = false; WorkerStatus = WorkerStatus.ExecutingSynch; CompletionCalled = false; PercentProgress = 0; UnpersistWorker(reader); }
/// <summary> /// Start the thread. Note: this method can be called again when /// the thread has called its OnCompletion() handler. /// </summary> public void Start() { Debug.Assert(Status != WorkerStatus.Running); Debug.Assert(InternalThread == null); // Initialize the socket pair once. if (SocketPair == null) SocketPair = KSocket.SocketPair(); // Initialize the variables used once per invocation. MsgQueue = new Queue<KThreadMsg>(); CancelFlag = false; BlockedFlag = false; Status = WorkerStatus.Running; FailException = null; InternalThread = new Thread(InternalRun); InternalThread.Start(); }
internal void PersistWorkerCleanUp(Exception ex) { if (ex == null) throw new InvalidOperationException("Exception was null."); WorkerStatus = WorkerStatus.Error; if (IsAsynch) { Exception x2 = ex; PersistComplete(PercentProgress, false, x2, null); } else throw ex; }
public void PersistPipeAsync(IPipe pipe, System.Xml.XmlWriter writer) { throw new Exception("The method or operation is not implemented."); if (IsBusy) { CancelAsync(); Reset(); } IsAsynch = true; WorkerStatus = WorkerStatus.ExecutingAsynch; PercentProgress = 0; CompletionCalled = false; AsynchOp = AsyncOperationManager.CreateOperation(null); new PersistDelegate(PersistWorker).BeginInvoke(pipe, writer, null, null); }
/// <summary> /// Updates the status of the worker with the given ID. /// </summary> /// <param name="id">The ID of the worker to update status for.</param> /// <param name="status">The status to update.</param> /// <param name="transaction">The transaction to use, if applicable.</param> public void UpdateWorkerStatus(long id, WorkerStatus status, IDbTransaction transaction) { throw new NotImplementedException(); }
public void PersistCompoundElement(ICompoundElement element, System.Xml.XmlWriter writer) { IsAsynch = false; WorkerStatus = WorkerStatus.ExecutingSynch; CompletionCalled = false; PercentProgress = 0; PersistWorker(element, writer); }
public ResumeWorkerEventArgs(WorkerStatus status, List<Exception> e) : this(status) { Exceptions.AddRange(e); }
public ResumeWorkerEventArgs(WorkerStatus status, Exception e) : this(status) { Exceptions.Add(e); }
public ResumeWorkerEventArgs(WorkerStatus status) : this() { Status = status; }
public PauseWorkerEventArgs(WorkerStatus status) : this() { Status = status; }
public void CancelAsync() { if (IsAsynch && IsBusy) { WorkerStatus = WorkerStatus.CancellationPending; } }
public void PersistPipe(IPipe pipe, System.Xml.XmlWriter writer) { IsAsynch = false; WorkerStatus = WorkerStatus.ExecutingSynch; CompletionCalled = false; PercentProgress = 0; PersistWorker(pipe, writer); }
public void PersistVarMgr(IVarMgr varMgr, System.Xml.XmlWriter writer) { IsAsynch = false; WorkerStatus = WorkerStatus.ExecutingSynch; CompletionCalled = false; PercentProgress = 0; PersistWorker(varMgr, writer); }
public void Reset() { if (!IsBusy) { AsynchOp = null; IsAsynch = false; WorkerStatus = WorkerStatus.Uninitialized; PercentProgress = 0; CompletionCalled = false; } else { throw new InvalidOperationException("Reset()"); } }
/// <summary> /// Updates the status of the worker with the given ID. /// </summary> /// <param name="id">The ID of the worker to update status for.</param> /// <param name="status">The status to update.</param> /// <param name="transaction">The transaction to use, if applicable.</param> public void UpdateWorkerStatus(long id, WorkerStatus status, IDbTransaction transaction) { const string Sql = @"UPDATE [BlueCollarWorker] SET [Status] = @Status, [UpdatedOn] = @Now WHERE [Id] = @Id;"; this.connection.Execute( Sql, new { Id = id, Now = DateTime.UtcNow, Status = status.ToString() }, transaction, null, null); }
internal void WrapUp(bool isValidContinue, IPipe pipe, Exception ex) { if (isValidContinue && !IsCancelled) { // --- set status's to completed when all is done WorkerStatus = WorkerStatus.Completed; PersistComplete(PercentProgress, false, ex, null); } else if (IsCancelled) { PersistComplete(PercentProgress, IsCancelled, ex, null); } else { // ex cannot be null if an error occured if (ex == null) ex = new FxExecutionErrorException("An persistance error occured."); WorkerStatus = WorkerStatus.Error; PersistComplete(PercentProgress, IsCancelled, ex, null); } }
public virtual void ExecuteTask() { Status = WorkerStatus.CompletedSuccess; OnWorkDone(); }
public virtual void Stop() { Status = WorkerStatus.ShouldStop; }
public void UnpersistSettings(ISettingsMgr target, System.Xml.XmlReader reader) { IsAsynch = false; WorkerStatus = WorkerStatus.ExecutingSynch; CompletionCalled = false; PercentProgress = 0; UnpersistWorker(target, reader); }
public WorkerStatusChangedEvent(Worker worker, WorkerStatus from, WorkerStatus to) { this.worker = worker; this.from = from; this.to = to; }
public void UnpersistSettingsAsync(ISettingsMgr target, System.Xml.XmlReader reader) { throw new Exception("The method or operation is not implemented."); if (IsBusy) { CancelAsync(); Reset(); } IsAsynch = true; WorkerStatus = WorkerStatus.ExecutingAsynch; PercentProgress = 0; CompletionCalled = false; AsynchOp = AsyncOperationManager.CreateOperation(null); new UnpersistDelegate(UnpersistWorker).BeginInvoke(target, reader, null, null); }
public void RunWorker() { while (true) { bool ajSuccess = false; resetEvent.WaitOne(); frameMutex.WaitOne(); //RNM // Process image this.workerStatus = WorkerStatus.Busy; if (processingImage.Width != grayBuffer.Width || processingImage.Height != grayBuffer.Height) grayBuffer = new Bitmap(processingImage.Width, processingImage.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); System.Drawing.Imaging.BitmapData imageBD = LockTotalBitmap(processingImage, System.Drawing.Imaging.ImageLockMode.ReadWrite); System.Drawing.Imaging.BitmapData grayBufferBD = LockTotalBitmap(grayBuffer, System.Drawing.Imaging.ImageLockMode.ReadWrite); try { // create unmanaged images UnmanagedImage imageUMI = new UnmanagedImage(imageBD); UnmanagedImage grayBufferUMI = new UnmanagedImage(grayBufferBD); // Apply grayscale and otsu filters if (this.probabilityMap == null) { // Grayscale Otsu Thresholding grayFilter.Apply(imageUMI, grayBufferUMI); otsuFilter.ApplyInPlace(grayBufferUMI); //Median mf = new Median(5); //mf.ApplyInPlace(grayBufferUMI); } else { // BPM Colour Thresholding probabilityMap.TresholdImage(imageUMI, grayBufferUMI); //Median mf = new Median(5); //mf.ApplyInPlace(grayBufferUMI); GaussianBlur gb = new GaussianBlur(3.0); Threshold t = new Threshold(127); gb.ApplyInPlace(grayBufferUMI); t.ApplyInPlace(grayBufferUMI); //AForge.Imaging.Filters.Erosion er = new AForge.Imaging.Filters.Erosion(); //er.ApplyInPlace(grayBufferUMI); } bool ccSuccess = componentFinder.FindBlobs(grayBufferUMI); // Create adjacency matrix if (ccSuccess) { ajSuccess = regionAdjacencyGraph.ConstructGraph(componentFinder.ObjectLabels, componentFinder.ObjectCount, processingImage.Width, processingImage.Height); } // If producing the graph has failed, for example due to too many regions, stop processing the current frame. if (!ajSuccess) { if (detectedMarkerList != null) detectedMarkerList.Clear(); if (permittedMarkerList != null) permittedMarkerList.Clear(); this.workerStatus = WorkerStatus.Finished; continue; } detectedMarkerList = markerDetector.FindMarkers(componentFinder, regionAdjacencyGraph); permittedMarkerList = markerDetector.PermitMarkers(detectedMarkerList, permittedCodes); } catch (Exception e) { //RNM resetEvent.Reset(); frameMutex.ReleaseMutex(); MessageBox.Show("An exception occurred during Marker Detection: " + e.Message); throw; } finally { processingImage.UnlockBits(imageBD); grayBuffer.UnlockBits(grayBufferBD); if (!ajSuccess) { resetEvent.Reset(); frameMutex.ReleaseMutex(); } } if (detectedMarkerList != null && permittedMarkerList.Count > 0) { //send marker xml. sendMarkerXml(permittedMarkerList); // Draw other UI components using (Graphics g = Graphics.FromImage(processingImage)) { Pen boundingBoxPen = new Pen(Color.Blue, 4.0f); boundingBoxPen.StartCap = System.Drawing.Drawing2D.LineCap.Round; boundingBoxPen.EndCap = System.Drawing.Drawing2D.LineCap.Round; Font markerFont = new Font("Arial", 16.0f); for (int marker = 0; marker < permittedMarkerList.Count; marker++) { int markerID = permittedMarkerList[marker].ID; string markerCode = permittedMarkerList[marker].Code; BoundingBox bb = componentFinder.ObjectBoundingBoxes[markerID]; g.DrawLine(boundingBoxPen, new System.Drawing.Point(bb.x1, bb.y1), new System.Drawing.Point(bb.x1, bb.y2)); g.DrawLine(boundingBoxPen, new System.Drawing.Point(bb.x1, bb.y2), new System.Drawing.Point(bb.x2, bb.y2)); g.DrawLine(boundingBoxPen, new System.Drawing.Point(bb.x2, bb.y2), new System.Drawing.Point(bb.x2, bb.y1)); g.DrawLine(boundingBoxPen, new System.Drawing.Point(bb.x2, bb.y1), new System.Drawing.Point(bb.x1, bb.y1)); } for (int marker = 0; marker < permittedMarkerList.Count; marker++) { int markerID = permittedMarkerList[marker].ID; string markerCode = permittedMarkerList[marker].Code; BoundingBox bb = componentFinder.ObjectBoundingBoxes[markerID]; g.DrawString(markerCode, markerFont, Brushes.Red, new PointF(bb.x1, bb.y2)); } } } this.workerStatus = WorkerStatus.Finished; workerTicks++; resetEvent.Reset(); frameMutex.ReleaseMutex(); } }
public void PersistProperties(IWorkSpaceProperties wsProperties, System.Xml.XmlWriter writer) { IsAsynch = false; WorkerStatus = WorkerStatus.ExecutingSynch; CompletionCalled = false; PercentProgress = 0; PersistWorker(wsProperties, writer); }