我需要从Visual Studio中调试Windows服务我无法运行服务,因此我正在使用Installutil.exe。什么是记录信息或调试Windows服务的最简单方法?
因此,每次构建后,我使用Installutil.exe,但我不能一步一步在我的代码中。
你知道任何简单的方法:
- 使用VS调试器来检查代码?
- 或在事件中记录一些消息,以便我可以跟踪发生了什么?
感谢
我需要从Visual Studio中调试Windows服务我无法运行服务,因此我正在使用Installutil.exe。什么是记录信息或调试Windows服务的最简单方法?
因此,每次构建后,我使用Installutil.exe,但我不能一步一步在我的代码中。
你知道任何简单的方法:
感谢
您可以使用日志如Log4Net写入到一个文件,但如果你想调试有一种方法来attach the debugger to a running process。
因此,在每次构建之后,我使用Installutil.exe,但是我无法通过 步执行我的代码。
如果您想在Visual Studio中调试服务,那么您可以执行以下操作。
在Program.cs
文件中定义:
private static void RunService()
{
var service = new YourService();
System.ServiceProcess.ServiceBase.Run(service);
}
//for debug only
private static void RunNoService()
{
using (var service = new YourService())
{
service.Start();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
}
在Main
方法
static void Main()
{
if (Environment.UserInteractive) //This is IMPORTANT
RunNoService();
else
RunService();
}
在服务定义Start
方法,这会从OnStart
具备的功能,修改您的OnStart
方法:
protected override void OnStart(string[] args)
{
Start();
}
Environment.UserInteractive
将检查服务是否从Visual Studio运行并让您调试它。
日志记录:
始终会记录您的活动为您服务。这将帮助您在服务生产中调试您的服务。您可以使用Log4Net或者您可以创建自己的自定义类以进行日志记录。即使记录到一个简单的文本文件将比没有任何东西更好。但是你必须记录日志,否则如果在生产中出现错误,它可能会变得非常令人沮丧。
调试在Visual Studio中的服务,我使用此代码的服务项目:
在的Program.cs:
static class Program
{
#if DEBUG
static AutoResetEvent sare = new AutoResetEvent(false);
#endif
static void Main()
{
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Service() };
ServiceBase.Run(ServicesToRun);
#else
Service service = new Service();
service.DebugServiceStopped += new Action(SetAutoResetEvent);
service.DebugStart();
sare.WaitOne();
#endif
}
#if DEBUG
private static void SetAutoResetEvent()
{
sare.Set();
}
#endif
}
在服务。CS(实际Service
类的文件),你需要添加这些代码部分:
#if DEBUG
public event Action DebugServiceStopped;
public void DebugStart()
{
OnStart(null);
}
#endif
protected override void OnStop()
{
#if DEBUG
DebugServiceStopped();
#endif
}
如果选择Debug
在Visual Studio中的配置,你将能够调试服务只是作为一个正常的应用程序,否则项目将被编译为一个真正的服务。
记录: 在Windows上存在Windows事件日志用来存储信息,警告和应用程序的错误。从服务的事件日志可以写入:
EventLog.WriteEntry("your log message", EventLogEntryType.Information); // or EventLogEntryType.Error,... depending on the entry type
我通常使用一些AOP工具,如PostSharp插入'Trace.WriteLine'调用(你也可以自己做)。当我需要排除故障时,我设置了[Trace Listener](http://msdn.microsoft.com/en-us/library/4y5y10s7(v = vs.110).aspx)。 – vcsjones