Methods for creating Windows services with. NET 1th/2 page _c# Tutorial

Source: Internet
Author: User
Tags time interval

Translator Explanation: I study C # through the translation, the article involves the Visual Studio.NET related operation, I all according to the Chinese version vs.net displays the information to handle, may let everybody not have the misunderstanding.

Author: Mark Strawmyer

We'll look at how to create an application that serves as a Windows service. Content contains what Windows services are, how to create, install, and debug them. The class that will use the System.ServiceProcess.ServiceBase namespace.


What is a Windows service?


A Windows Service application is an application that needs to run for a long time and is particularly suited for server environments. It has no user interface and does not produce any visual output. Any user messages will be written to the Windows event log. When the computer starts, the service automatically starts running. They do not have to be logged on by the user, and they can run in any user environment that includes the system. With the Service Control Manager, Windows services are controllable and can be terminated, paused, and started when needed.

Windows services, previous NT services, were introduced as part of the Windows NT operating system. They are not in Windows 9x and Windows Me. You need to use an NT-level operating system to run Windows services, such as Windows NT, Windows Professional, or Windows Server. For example, products in the form of Windows services are Microsoft Exchange, SQL Server, and other Windows Time services that set the computer clock.


Create a Windows service

The service we are about to create will do nothing but demo. When a service is started, an entry information is registered in a database to indicate that the service has been started. During a service run, it periodically creates a database project record within a specified time interval. The last database record is created when the service is stopped. This service automatically registers records of the Windows application log when it starts or stops successfully.

Visual Studio. NET makes it a fairly simple thing to create a Windows service. The instructions for starting our Demo service program are summarized below.

1. Create a new project
2. Choose Windows Services from a list of available project templates
3. Designer opens in design mode
4. Drag a Timer object from the Component table of the toolbox to the design surface (note: Make sure to use the timer from the list of components rather than from the list of Windows Forms)
5. Set Timer property, Enabled property is False,interval property 30000 ms
6. Switch to the Code view page (press F7 or select the code in the View menu) and add functionality to the service


Composition of Windows Services

In the code that follows your class, you will notice that the Windows service you created expands the System.ServiceProcess.Service class. All in. net method to build Windows services must extend this class. It will require your service to overload the following methods, which are included by Visual Studio by default.

dispose– clears any managed and uncontrolled resources (managed and unmanaged)
onstart– Control Service Launch
onstop– Control Service stopped

database table Script Sample

The database tables used in this example are created using the following T-SQL script. I chose the SQL Server database. You can easily modify this example to make it run under Access or any other database you choose.

CREATE TABLE [dbo]. [Myservicelog] (
[In_logid] [INT] IDENTITY (1, 1) not NULL,
[Vc_status] [nvarchar] (40)
COLLATE SQL_Latin1_General_CP1_CI_AS not NULL,
[Dt_created] [DateTime] Not NULL
) on [PRIMARY]


Examples of Windows services

Here is all the source code for the Windows service I named MyService. Most of the source code is generated automatically by Visual Studio.

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Data.SqlClient;
Using System.Diagnostics;
Using System.ServiceProcess;

Namespace Codeguru.mywindowsservice
{
public class MyService:System.ServiceProcess.ServiceBase
{
Private System.Timers.Timer timer1;
<remarks>
Required designer variable.
</remarks>
Private System.ComponentModel.Container components = null;

Public MyService ()
{
This are required by the Windows.Forms
Component Designer.
InitializeComponent ();
}

The main entry point for the process
static void Main ()
{
System.serviceprocess.servicebase[] ServicesToRun;

ServicesToRun = new system.serviceprocess.servicebase[]
{New MyService ()};

System.ServiceProcess.ServiceBase.Run (ServicesToRun);
}

<summary>
Required to Designer support-do not modify
The contents is with the Code Editor.
</summary>
private void InitializeComponent ()
{
This.timer1 = new System.Timers.Timer ();
((System.ComponentModel.ISupportInitialize)
(This.timer1)). BeginInit ();
//
Timer1
//
This.timer1.Interval = 30000;
this.timer1.Elapsed =
New System.Timers.ElapsedEventHandler (this.timer1_elapsed);
//
MyService
//
This. ServiceName = "My Sample Service";
((System.ComponentModel.ISupportInitialize)
(This.timer1)). EndInit ();

}

  ///<summary>
  ///Clean up any resources being used.
  ///</summary>
   protected override void Dispose (bool disposing)
   {
     if (disposing)
     {
      if ( Components!= null)
      {
         Components. Dispose ();
     }
    }
     Base. Dispose (disposing);
  }

  ///<summary>
  ///Set things in motion so your service can does its work.
  ///</summary>
   protected override void OnStart (string[] args)
   {
     this.timer1.Enabled = true;
     this. LogMessage ("Service started");
  }

  ///<summary>
  ///Stop this service.
  ///</summary>
   protected override void OnStop ()
   {
  & nbsp;  this.timer1.Enabled = false;
     this. LogMessage ("Service Stopped");
  }

/*
* Respond to the Elapsed event of the timer control
*/
private void Timer1_elapsed (object sender,
System.Timers.ElapsedEventArgs e)
{
This. LogMessage ("Service Running");
}

/*
* LOG specified message to database
*/
private void LogMessage (String message)
{
SqlConnection connection = null;
SqlCommand command = NULL;
Try
{
Connection = new SqlConnection (
"Server=localhost;database=sampledatabase;integrated
Security=false; User Id=sa; password=; ");
Command = new SqlCommand (
"INSERT into Myservicelog (Vc_status, dt_created)
VALUES (' + message + ', GETDATE ()) ', connection);
Connection. Open ();
int numrows = command. ExecuteNonQuery ();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine (ex. message);
}
Finally
{
Command. Dispose ();
Connection. Dispose ();
}
}
}
}

Current 1/2 page 12 Next read the full text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.