Create and Control Windows Services--Not a Slap Shot, but Al

80酷酷网    80kuku.com

  services|window|高级Not a Slap Shot, but Almost as Fast
Creating the service using .NET is fairly straightforward. You use the .NET Framework's System.ServiceProcess namespace and four classes within it: ServiceBase, ServiceInstaller, ServiceProcessInstaller, and ServiceController. These classes provide most of the functionality you need to create a service (see Figure 1).

   
Figure 1 | Everything You Need in One Namespace. Click here.


The ServiceBase class defines methods a derived class can override so the Service Control Manager can control a service—including OnStart(), OnStop(), OnPause(), and OnContinue(). Furthermore, a service can override the OnCustomCommand() function to carry out specific operations sent to it programmatically by an external service controller (more on this later). Implementing these functions in your derived class gives you the necessary structure of a service:

protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
protected override void OnPause()
{
}
protected override void OnContinue()
{
}
Allow your service to begin execution by defining an entry point into your executable, as you would with a regular executable. Within the Main() function, create an instance of your class and call the Run() method defined by the ServiceBase base class. If you want your executable to support multiple services, create an array of ServiceBase objects with each element corresponding to one of your defined services:

static void Main()
{
System.ServiceProcess.ServiceBase[] MyServices;

MyServices = new System.ServiceProcess.ServiceBase[] { new Service1, new Service2() };

System.ServiceProcess.ServiceBase.Run(MyServices);
}
Note that Run() does not start your service. In other words, you won't receive an OnStart() call from the Run() method itself. As I mentioned before, the Service Control Manager controls the service by calling the necessary controlling functions.

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: