This project has moved and is read-only. For the latest updates, please go here.

Get the Process ID for the newly spawned process

Apr 24, 2012 at 3:56 PM

Is there a way to get at the Process ID for a process that has been created as a result of a scheduled task?  As an example, I can use the following to register a task and have it launch immediately (on registration):

TaskDefinition taskDefinition = taskService.NewTask();
RegistrationTrigger trigger = new RegistrationTrigger();
ExecAction action = new ExecAction("notepad.exe", "", "c:\mydir");
TaskFolder folder = taskService.GetFolder("MyFolder");
Task task = folder.RegisterTaskDefinition("KrisTask", taskDefinition);

The task / TaskDefinition classes do  not expose PIDs, which makes sense since they don't necessarily correspond to a running process.   The RunningTask class exposes an enginePID, however this appears to be the PID for the taskeng.exe process that spawned the process (notepad.exe in my example).  Looking at the Task Scheduler GUI, the History for a Task contains a "Create Task Process" event which lists the correct process id:

     instance "notepad.exe"  with process ID 9888.

What is the best way, if any, to retrieve the process ID for the spawned process?  For now, I am going to do a manual set difference of the running processes before and after the RegisterTaskDefinition() call (with some arbitrary delay that is hopefully "long enough") and filter by the executable name.  This should work for my specific case, however it will not be a long-term solution.


Apr 24, 2012 at 9:25 PM

I believe, though not completely sure, that you can get the process ID for a running task by looking at the EnginePID property for the RunningTask instances exposed when calling the TaskService.GetRunningTasks method.

Apr 24, 2012 at 10:24 PM
Edited Apr 24, 2012 at 10:25 PM

Thanks for the response!  Unfortunately the RunningTask.EnginePID in the RunningTaskCollection appears to correspond to the taskeng.exe and taskhost.exe processes, rather than the process that was spawned (notepad.exe in my example).  My test code is :


foreach (RunningTask t in taskService.GetRunningTasks())
	Console.WriteLine("{0}\n\tTask PID: {1}\n\tCurrent Action: {2}", t.Name, t.EnginePID, t.CurrentAction);

Note that the output from this test is :


 Task PID: 1234 (process id of taskeng.exe)

 Current Action: notepad.exe

While attempting to print the information for the RunningTask in the foreach statement above, I noticed that I don't [have] access to the process name in the way I would expect - t.CurrentAction has the process name.