C# 在服务启动时获取服务的进程ID

C# 在服务启动时获取服务的进程ID,c#,service,C#,Service,我创建了一个Windows服务 我需要在运行时获取进程的PID并将其保存到DB 在我的OnStart上 timer1 = new Timer(); double Interval = Convert.ToDouble(ConfigurationManager.AppSettings["intervalInSeconds"].ToString()); this.timer1.Interval = Interval * 1000; this.timer1.Elapsed += new System.

我创建了一个Windows服务

我需要在运行时获取进程的PID并将其保存到DB

在我的OnStart上

timer1 = new Timer();
double Interval = Convert.ToDouble(ConfigurationManager.AppSettings["intervalInSeconds"].ToString());
this.timer1.Interval = Interval * 1000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;

Library.WriteErrorLog("service started");
我试着用计算机获取PID


GetService但它不起作用。

您可以从Managementobject-like列表中查询

private static uint GetProcessIDByServiceName(string serviceName)
 {
   uint processId = 0;
   string qry = "SELECT PROCESSID FROM WIN32_SERVICE WHERE NAME = '" + serviceName + "'";
   System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(qry);
   foreach (System.Management.ManagementObject mngntObj in searcher.Get())
    {
      processId = (uint)mngntObj["PROCESSID"];
    }
    return processId;
 }

Process.GetCurrentProcess().Id
?我的代码中的进程是什么?我试图使用它,但总是得到0 timer1=new Timer();双间隔=Convert.ToDouble(ConfigurationManager.AppSettings[“intervalInSeconds”].ToString());this.timer1.Interval=间隔*1000;this.timer1.appeased+=新系统.Timers.ElapsedEventHandler(this.timer1_勾号);timer1.Enabled=true;uint PID=GetProcessIDByServiceName(“MessagingService.exe”);Library.WriteErrorLog(“服务启动PID=“+PID.ToString());但它正在运行我在进程列表中看到了