Search code examples
c#windowsmultithreadingservicepid

How to find Windows service by PID and thread ID?


In my C# application I have a PID and threadID of a Windows service. How can I find which service it is (note: e.g., a single instance of svchost.exe can host multiple services)? Either directly in C# or calling some other utility is fine with me.

Process Hacker can show the service name (properties of process -> tab threads -> column service).

So far I have found the process and also the thread:

var p = Process.GetProcessById(pid);
var t = p.Threads.Cast<ProcessThread>().SingleOrDefault(t => t.Id == threadId);

How to go on? Alternatives?


Solution

  • In general, you can't. There is no 1:1 relationship between threads and services. A single thread can be running multiple services, and a single service can (and typically does) have multiple threads.

    Process Hacker is likely using some sort of heuristic, for example, tracing the call stack for the thread and identifying the DLL that svchost.exe is running. Or perhaps it assumes that the thread is the same one that called ServiceMain(); there might be an undocumented method of identifying that one.