我一直在浏览MSDN上的Walkthrough: Creating a Windows Service Application in the Component Designer。
我有一些代码,我的服务已安装:
我的代码如下:
namespace WindowsServiceWalkthrough
{
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;
using System.Runtime.InteropServices;
public partial class MyNewService : ServiceBase
{
private int _eventId;
public MyNewService()
{
InitializeComponent();
if (! EventLog.SourceExists("MySource"))
{
EventLog.CreateEventSource(
"MySource",
"MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool SetServiceStatus(IntPtr handle, ref ServiceStatus serviceStatus);
protected override void OnStart(string[] args)
{
var serviceStatus = new ServiceStatus
{
dwCurrentState = ServiceState.SERVICE_RUNNING,
dwWaitHint = 100000
};
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
eventLog1.WriteEntry("My Event Log: In OnStart method", EventLogEntryType.Information);
var timer = new Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += OnTimer;
timer.Start();
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(ServiceHandle, ref serviceStatus);
}
public void OnTimer(object sender, ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
eventLog1.WriteEntry("Monitoring the System", EventLogEntryType.Information, _eventId++);
}
protected override void OnStop()
{
}
}
public enum ServiceState
{
SERVICE_STOPPED = 0x00000001,
SERVICE_START_PENDING = 0x00000002,
SERVICE_STOP_PENDING = 0x00000003,
SERVICE_RUNNING = 0x00000004,
SERVICE_CONTINUE_PENDING = 0x00000005,
SERVICE_PAUSE_PENDING = 0x00000006,
SERVICE_PAUSED = 0x00000007,
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatus
{
public long dwServiceType;
public ServiceState dwCurrentState;
public long dwControlsAccepted;
public long dwWin32ExitCode;
public long dwServiceSpecificExitCode;
public long dwCheckPoint;
public long dwWaitHint;
};
}
但是,当我尝试从服务窗口启动服务时,出现以下错误:
如果我尝试使用net start MyNewService
从控制台启动它,我会收到以下错误:
服务未响应控制功能。
输入NET HELPMSG 2186即可获得更多帮助。
然后,帮助信息类似于窗口,即
服务未响应控制功能。
如何修复\ debug this?
我正在运行Windows 8.1并使用.NET 4.5.2
答案 0 :(得分:2)
要调试问题,您可以执行以下操作:
尝试添加到OnStart
方法(可能已开始):
System.Diagnostics.Debugger.Launch();
解决方案应该在VS中打开,当您启动服务时,它应该提示您在VS实例中运行调试器。 您可以在与您的问题非常相似的问题中找到一些替代解决方案:How to debug the .NET Windows Service OnStart method?
快乐的调试!
答案 1 :(得分:1)
感谢DDan关于附加调试器的建议,我能够解决我的问题。
我的问题是我试图监视程序文件目录中的服务器没有权限的文件夹,我收到错误The directory name [path of folder] is invalid..
。
我将目录更改为C:\ temp,服务运行正常。
我会将此作为评论留下,但目前还不具备所需的声誉。希望这会对某人有所帮助。