以下更改允许您像调试任何其他控制台应用程序一样调试 Windows 服务。
将此类添加到您的项目中:
public static class WindowsServiceHelper
{
[DllImport("kernel32")]
static extern bool AllocConsole();
public static bool RunAsConsoleIfRequested<T>() where T : ServiceBase, new()
{
if (!Environment.CommandLine.Contains("-console"))
return false;
var args = Environment.GetCommandLineArgs().Where(name => name != "-console").ToArray();
AllocConsole();
var service = new T();
var onstart = service.GetType().GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
onstart.Invoke(service, new object[] {args});
Console.WriteLine("Your service named '" + service.GetType().FullName + "' is up and running.\r\nPress 'ENTER' to stop it.");
Console.ReadLine();
var onstop = service.GetType().GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
onstop.Invoke(service, null);
return true;
}
}
然后添加-console
到 windows 服务项目的调试选项。
最后将其添加Main
到Program.cs
:
// just include this check, "Service1" is the name of your service class.
if (WindowsServiceHelper.RunAsConsoleIfRequested<Service1>())
return;
来自我的博客文章调试 Windows 服务的更简单方法