Debugging Windows service is a common issue.
The common solution is to select attach to process in the debugger after the service is run.
However, this method also has some limitations, such asCodeIt is basically difficult to debug. when attach arrives at our service, this part of code has been executed. so someone suggested that you could write another project to call this onstart method, or move the code in the onstart method to another project for testing. however, these methods are not debugged in the form of a Windows service, and cannot reflect the running status of the service in the most real way (such as permission issues and other environmental issues ).
My approach is to add "debugger. launch () "call. When the service is running here, a dialog box for selecting the debugger will pop up and paused at the current position. in this way, we can manually start the debugger in the code.
The sample code is as follows:
UsingSystem. diagnostics;
Public Partial ClassMyservice: servicebase {
PublicMyservice (){
Initializecomponent ();
}
Protected Override VoidOnstart (String[] ARGs ){
# IfDebug
Debugger. Launch ();// Launches and attaches a debugger to the process.
# Endif
// Todo: add your initialize code here.
}
Protected Override VoidOnstop (){
}
}