如何管理我们本地计算机上的 Windows 服务应用程序






4.91/5 (24投票s)
本文将演示如何在本地计算机上管理 Windows 服务应用程序。
目录

引言
Microsoft Windows 服务(以前称为 NT 服务)允许您创建在自己的 Windows 会话中运行的长时间运行的可执行应用程序。 这些服务可以在计算机启动时自动启动、可以暂停和重新启动,并且不显示任何用户界面。 这些特性使得服务非常适合在服务器上使用,或者在您需要不干扰在同一台计算机上工作的其他用户的长时间运行的功能时使用。
参考 - MSDN
在本文中,我们将创建一个应用程序,以获取当前已安装的服务应用程序的列表及其状态,以及如何在您的本地计算机上控制(例如,我们可以同时停止或启动多个服务)每个服务应用程序。
背景
Windows 服务应用程序通常用于各种目的,如推送拉取数据传输、电子邮件、系统监视等。 我关心的是如何管理本地服务器/远程服务器中的所有自定义服务应用程序,这就是为什么我需要创建工具来获取本地/远程计算机上指定服务应用程序的所有状态。
服务类型
您可以使用 .NET Framework 在 Visual Studio 中创建两种类型的服务。
- Win32OwnProcess: 仅在进程中为服务的服务分配类型
Win32OwnProcess
。 - Win32ShareProcess: 与另一个服务共享进程的服务分配类型
Win32ShareProcess
。
*注意:您可以通过查询 ServiceType
属性来检索服务类型。
如果您查询在 Visual Studio 中未创建的现有服务,您可能会偶尔看到其他服务类型。 有关这些的更多信息,请参阅 ServiceType
。
Using the Code
Microsoft Visual Studio .NET Framework 2.0 / 更新版本提供了命名空间 System.ServiceProcess
,我们将使用在上述命名空间中找到的 ServiceController
类。 这个类代表一个 Windows 服务,允许您连接到 Windows 服务,操作该服务并获取有关服务的信息。
您可以下载示例源代码以获得该程序的完整图片。
示例
public partial class Manager : Form
{
//string strServiceName = "";
public string strServerName = "Local";
class ServiceInfo
{
private string strName, strStatus;
public ServiceInfo(string sName, string sStatus)
{
strName = sName;
strStatus = sStatus;
}
public string ServiceName
{
get { return strName; }
}
public string ServiceStatus
{
get { return strStatus; }
}
}
private ArrayList ALWServiceInfo;
public Manager()
{
InitializeComponent();
ALWServiceInfo = new ArrayList();
}
private void Manager_Load(object sender, EventArgs e)
{
}
private void getWindowsServices()
{
ServiceController[] objArrServices;
try
{
if ((this.comboBoxServerNameOrIPs.Text == "Local")
|| this.comboBoxServerNameOrIPs.Text ==
System.Environment.MachineName.ToString ()
|| this.comboBoxServerNameOrIPs.Text == "127.0.0.1")
{
objArrServices = ServiceController.GetServices();
}
else
objArrServices = ServiceController.GetServices
(comboBoxServerNameOrIPs.Text);
ALWServiceInfo.Clear();
foreach (ServiceController objServiceController in objArrServices)
{
ALWServiceInfo.Add(new ServiceInfo
(objServiceController.ServiceName,
objServiceController.Status.ToString()));
}
dgServices.DataSource = ALWServiceInfo;
dgServices.Refresh();
}
catch (Exception ex)
{
MessageBox.Show("Error Occurred: " + ex.Message);
}
}
private void buttonConnect_Click(object sender, EventArgs e)
{
this.getWindowsServices();
}
private void buttonClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void setCommandButton()
{
//get the status of the service.
string strServerStatus = WSControllerAgent.Status.ToString();
//check the status of the service and enable the
//command buttons accordingly.
if (strServerStatus == "Running")
{
//check to see if the service can be paused
if (WSControllerAgent.CanPauseAndContinue == true)
{
ButtonPause.Enabled = true;
}
else
{
ButtonPause.Enabled = false;
}
ButtonStop.Enabled = true;
ButtonStart.Enabled = false;
}
else if (strServerStatus == "Paused")
{
ButtonStart.Enabled = true;
ButtonPause.Enabled = false;
ButtonStop.Enabled = true;
}
else if (strServerStatus == "Stopped")
{
ButtonStart.Enabled = true;
ButtonPause.Enabled = false;
ButtonStop.Enabled = false;
}
}
private void getSelectedServiceStatus()
{
try
{
}
catch (Exception ex)
{
MessageBox.Show("Error Occurred: " + ex.Message);
}
}
private void dgServices_MouseClick(object sender, MouseEventArgs e)
{
this.onLoadWServices(this.dgServices.CurrentCell.Value.ToString());
}
private void onLoadWServices(string strServiceName)
{
try
{
ServiceController[] AvailableServices =
ServiceController.GetServices(".");
if (strServiceName != "")
{
foreach (ServiceController AvailableService in AvailableServices)
{
//Check the service
if (AvailableService.ServiceName == strServiceName)
{
this.WSControllerAgent.ServiceName = strServiceName;
this.setCommandButton();
return;
}
}
}
}
catch
{
MessageBox.Show("The Service is not installed on this Machine",
"Service is not available");
this.Close();
Application.Exit();
}
}
private void ButtonStart_Click(object sender, EventArgs e)
{
//check the status of the service
if (WSControllerAgent.Status.ToString() == "Paused")
{
WSControllerAgent.Continue();
}
else if (WSControllerAgent.Status.ToString() == "Stopped")
{
//get an array of services this service depends upon, loop through
//the array and prompt the user to start all required services.
ServiceController[] ParentServices = WSControllerAgent.ServicesDependedOn;
try
{
//if the length of the array is greater than or equal to 1.
if (ParentServices.Length >= 1)
{
foreach (ServiceController ParentService in ParentServices)
{
//make sure the parent service is running or at least paused.
if (ParentService.Status.ToString() != "Running" ||
ParentService.Status.ToString() != "Paused")
{
if (MessageBox.Show("This service is required.
Would you like to also start this service?\n" +
ParentService.DisplayName, "Required Service",
MessageBoxButtons.YesNo).ToString() == "Yes")
{
//if the user chooses to start the service
ParentService.Start();
ParentService.WaitForStatus
(ServiceControllerStatus.Running);
}
else
{
//otherwise just return.
return;
}
}
}
}
WSControllerAgent.Start();
WSControllerAgent.WaitForStatus
(System.ServiceProcess.ServiceControllerStatus.Running);
}
catch (Exception ex)
{
MessageBox.Show("Error Occurred: " + ex.Message.ToString());
}
this.setCommandButton();
}
}
private void ButtonPause_Click(object sender, EventArgs e)
{
//check to see if the service can be paused and continue
if (WSControllerAgent.CanPauseAndContinue == true)
{
//check the status of the service
if (WSControllerAgent.Status.ToString() == "Running")
{
WSControllerAgent.Pause();
}
WSControllerAgent.WaitForStatus
(System.ServiceProcess.ServiceControllerStatus.Paused);
this.setCommandButton();
}
}
private void ButtonStop_Click(object sender, EventArgs e)
{
//check to see if the service can be stopped.
if (WSControllerAgent.CanStop == true)
{
//get an array of dependent services, loop through the array and
//prompt the user to stop all dependent services.
ServiceController[] DependentServices =
WSControllerAgent.DependentServices;
//if the length of the array is greater than or equal to 1.
if (DependentServices.Length >= 1)
{
foreach (ServiceController DependentService in DependentServices)
{
//make sure the dependent service is not already stopped.
if (DependentService.Status.ToString() != "Stopped")
{
if (MessageBox.Show("Would you like to also
stop this dependent service?\n"
+ DependentService.DisplayName
, "Dependent Service"
, MessageBoxButtons.YesNo).ToString() == "Yes")
{
// not checking at this point whether the
// dependent service can be stopped.
// developer may want to include this check
// to avoid exception.
DependentService.Stop();
DependentService.WaitForStatus
(ServiceControllerStatus.Stopped);
}
else
{
return;
}
}
}
}
//check the status of the service
if (WSControllerAgent.Status.ToString() ==
"Running" || WSControllerAgent.Status.ToString() == "Paused")
{
WSControllerAgent.Stop();
}
WSControllerAgent.WaitForStatus
(System.ServiceProcess.ServiceControllerStatus.Stopped);
this.setCommandButton();
}
}
}
结论
希望它对您有所帮助。 享受吧!
历史
- 2009 年 8 月 5 日:初始发布