Windows Service debugging process

Source: Internet
Author: User

For the first time, I wrote a windows service in C #. In fact, the implementation is relatively simple. It is to start the remoting connection, but it is annoying for me to debug the windws service for the first time. No experience, and you cannot set breakpoints like debugging other windows programs, and you cannot see the running process. After checking some relevant information, I had some debugging experience. I hereby leave a pen for future use.

Source code:

Code
Static void Main ()
{
ServiceBase [] ServicesToRun;

// Multiple user services can be run in the same process. To
// Add another service to this process. Please change the downstream
// Create another service object. For example,
//
// ServicesToRun = new ServiceBase [] {new Service1 (), new MySecondUserService ()};
//
ServicesToRun = new ServiceBase [] {new TeamWorldService ()};

ServiceBase. Run (ServicesToRun );
// TeamWorldService obj = new TeamWorldService ();
// Obj. OnStart ();
}

TeamWorldService:

 

Code
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Diagnostics;
Using System. ServiceProcess;
Using System. Text;
Using System. IO;
Using Tribal. TeamWorld. API;
Using Tribal. BaseClasses;
Using Tribal. TeamWorld. Remoting;
Using Tribal. TeamWorld. Implementation;

Namespace Tribal. TeamWorld. Service
{
Partial class TeamWorldService: ServiceBase
{
Private RemotingInterface _ remotingInterface = null;
Private MainController _ mainController = null;
Public TeamWorldService ()
{
InitializeComponent ();//

}

Protected override void OnStart (string [] args)
{
This. AddTextLine ("Starting server (" + DateTime. Now. ToString () + ")");

Try
{
This. AddTextLine ("Initializing MainController ");
This. _ mainController = MainController. GetInstance ();
}
Catch (Exception ex)
{
This. PrintExceptions (ex );
}

If (this. _ mainController! = Null)
{
This. AddTextLine ("Connecting userinterface to LogController ");
}

Try
{
This. AddTextLine ("Starting MainController ");
This. _ mainController. Start ();
}
Catch (Exception exc)
{
This. PrintExceptions (exc );
}

Try
{
This. AddTextLine ("Starting. NET RemotingInterface ");
This. _ remotingInterface = new RemotingInterface ();
This. _ remotingInterface. StartServing ();
}
Catch (Exception exc)
{
This. PrintExceptions (exc );
}
}

Protected override void OnStop ()
{

This. _ remotingInterface. StopServing ();
This. _ mainController. Stop ();
This. AddTextLine ("End. NET RemotingInterface ");

}

Private void PrintExceptions (Exception exc)
{
Exception current = exc;
While (current! = Null)
{
This. AddTextLine (current. Message );
This. AddTextLine (current. StackTrace );

Current = current. InnerException;
}
}

Private void AddTextLine (string line)
{
Try
{
FileStream fs = new FileStream (@ "C: \ TeamWorldServiceLog.txt", FileMode. OpenOrCreate, FileAccess. Write );

StreamWriter m_streamWriter = new StreamWriter (fs );

M_streamWriter.BaseStream.Seek (0, SeekOrigin. End );

M_streamWriter.WriteLine (line + "\ r \ n ");

M_streamWriter.Flush ();

M_streamWriter.Close ();

Fs. Close ();
}
Catch (Exception ex)
{

}
}
}
}

Method 1: Write logs
It is the most traditional method for debugging windows service and a useful method for debugging services. However, debugging is still unclear. You need to add all the log writing methods where you think an error may occur. The code above adopts the AddTextLine function.

Method 2: attach Process
You can set breakpoints for single-step debugging like debugging a normal widows program. However, you must install and start the service before you can append the service process. You can run the OnStart function while attaching the service. Therefore, Onstart cannot be debugged. However, I can load debugging by setting the Service Startup latency.
The procedure is as follows:
1. Set the Service Startup latency,

Code
Private System. Timers. Timer timerDelay;

Protected override void OnStart (string [] args)
{
Try
{

/// Delay start the SynData 30 seconds
TimerDelay = new System. Timers. Timer (30000 );
TimerDelay. Elapsed + = new System. Timers. ElapsedEventHandler (timerDelay_Elapsed );
TimerDelay. Start ();
}
Catch (Exception ex)
{
This. PrintExceptions (ex );
}
}

Void timerDelay_Elapsed (object sender, System. Timers. ElapsedEventArgs e)
{
TimerDelay. Enabled = false;
TimerDelay. Close ();
// The code you want to add
//. To do ..
}

Note: The normal service startup time is about 30 seconds. If the service startup time exceeds 30 seconds, an error is returned !, Therefore, do not perform too many operations in OnStart. You can also use this delay method to start the service to prevent timeout during service startup.
2. First install the service and then start the service.
3. Enable vs2005 debugging-> attach to the process and select your service process (if not found, check to display all user processes.

Method 3:
I think this debugging is the most helpful to me.
In the Main function, comment out the original automatically generated code. Note that the red part must be manually added according to your service name.
// ServiceBase [] ServicesToRun;

// Multiple user services can be run in the same process. To
// Add another service to this process. Please change the downstream
// Create another service object. For example,
//
// ServicesToRun = new ServiceBase [] {new Service1 (), new MySecondUserService ()};
//
// ServicesToRun = new ServiceBase [] {new TeamWorldService ()};

// ServiceBase. Run (ServicesToRun );
//************************************** ****
TeamWorldService obj = new TeamWorldService ();
Obj. OnStart ();
//************************************** ****
Change protected override void OnStart (string [] args) to public void OnStart ().
, Set your breakpoint, and press F5 to start debugging.

The above are some of the methods obtained after you debug the widows service. To continue accumulating in the future.

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.