This project has moved. For the latest updates, please go here.

Event for stop/Exit of started task

Dec 17, 2015 at 3:32 PM
Is there an Event that gets raised when the process that I start via a Task gets stopped?

Currently I use
var processlist = Process.GetProcesses();

foreach(var theprocess in processlist)
 {
          if (theprocess.ProcessName != "DEMO")
                 continue;

          theprocess.WaitForExit();
          break;
 }
to enum all processes and If I find my started program I wait for Exit. Is there a better way?
Coordinator
Dec 18, 2015 at 12:31 AM
In fact, a brand new feature does allow this. Try the following:
private TaskEventWatcher watcher;

// Create and configure a new task watcher for the task folder
private void SetupWatcher(Task task)
{
   if (task != null)
   {
      // Set up a watch over the supplied task.
      watcher = new TaskEventWatcher(task);

      // Assign a SynchronizingObject to a local UI class to synchronize the events in this thread.
      watcher.SynchronizingObject = this;

      // Only watch for task events that indicate success (102), failure (103), or termination (111)
      watcher.Filter.EventIds = new int[] { 102, 103, 111 };

      // Assign an event handler for when events are recorded
      watcher.EventRecorded += Watcher_EventRecorded;
      
      // Start watching the task by enabling the watcher
      watcher.Enabled = true;
   }
}

// Cleanup and release the task watcher
private void TearDownWatcher()
{
   if (watcher != null)
   {
      // Unhook the event
      watcher.EventRecorded -= Watcher_EventRecorded;
      // Stop watching for events
      watcher.Enabled = false;
      // Initiate garbage collection for the watcher
      watcher = null;
   }
}

// Do something when task events occur
private void Watcher_EventRecorded(object sender, TaskEventArgs e)
{
   DoSomething(e.TaskName);
}
Dec 18, 2015 at 10:46 AM
Hi,

thanks for the answer.

I adapted it and created different watchers and EventRecorded handlers for each Event that I care, but non gets fired. I commented the deletion of the Task out and in the history in Task Scheduler I saw that the 102 Event is logged there, but my handler never got called.

André
Coordinator
Dec 21, 2015 at 6:01 PM
Sometimes with these event handlers, there can be threading problems. I have posted a sample project just for task watching in the documentation for Task Events. Look there for some further hints on how to get this working in your code and post back here if you are unable to resolve your issue. I have confirmed that it works by building the project posted in the documentation.