2010-08-19 78 views
0

嘿家伙,我已经在网上关于一些关于创建和安装Windows服务的教程,似乎不断陷入困境。我遵循教程here,它似乎在工作,但它不是100%。这是使用代码IM:坚持实施Windows服务

namespace SuperService 
{ 
partial class Logger : ServiceBase 
{ 
    public Logger() 
    { 
     InitializeComponent(); 
    } 

    void timer1_Tick(object sender, EventArgs e) 
    { 
     LogEvent("This Timer has been ticked!", EventLogEntryType.Information); 
    } 

    protected override void OnStart(string[] args) 
    { 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Start(); 
     LogEvent("This SuperService has started!", EventLogEntryType.Information); 
    } 

    protected override void OnStop() 
    { 
     LogEvent("This SuperService has stopped.", EventLogEntryType.Information); 
    } 

    protected override void OnPause() 
    { 
     base.OnPause(); 
     timer1.Stop(); 
    } 

    protected override void OnContinue() 
    { 
     base.OnContinue(); 
     timer1.Start(); 
    } 

    static void LogEvent(String Message, EventLogEntryType type) 
    { 
     String source = "Logger"; 
     String log = "Application"; 
     if (!EventLog.SourceExists(source)) 
     { 
      EventLog.CreateEventSource(source, log); 
     } 

     EventLog eLog = new EventLog(); 
     eLog.Source = source; 

     eLog.WriteEntry(Message, type); 
    } 
} 
} 

现在,当我启动服务它显示了以下两个事件后检查事件查看器:

这SuperService已经开始了!

服务已成功启动。

所以它似乎有点工作,我没有看到是由timer1_Tick触发的事件。有谁知道为什么或可以指出我在正确的方向吗?提前致谢。

+0

定时器的间隔是多少?确保它不是0. – 2010-08-19 20:43:56

+0

定时器的间隔在哪里设置?也许在设计师?它有什么价值? – 2010-08-19 20:45:20

+0

其60000和启用 – 2010-08-19 20:45:46

回答

1

您是否使用System.Threading.Timer而不是System.Windows.Forms.Timer? 您使用有有同样的问题和切换成功

更多信息System.Threading.Timer的用户评论教程的链接(从你的链接所): Problem with System.Timers.Timer not firing in a Windows service

+0

你是对的,因为我怀疑。我改变了代码,现在它可以工作。谢谢! – 2010-08-20 16:28:18

1

另外,通过topshelf,windows服务更容易。开源项目,允许您将您的服务编写为控制台应用程序/ POCO,但可以从“服务容器”中提取安装/卸载/调试支持,以便将所有胶水抽象化。

myservice         (to run as console app for debugging) 
myservice /install 
myservice /uninstall 
myservice /instance:{instance_name} 
0

编辑:这是一个SO回答,涵盖了我在下面写的东西。

Windows Service Stops Automatically


我相信,如果它“认为”的服务无关的Windows将停止服务。我不记得做这个的确切的底层“API”。几年前我和它一起战斗过。


在你的事件日志中是否有某些东西在写着:“我的服务没有做到,终止”。或者是一些传达这种言辞的信息?

+0

不。只是我在帖子中提到的两个 – 2010-08-19 21:04:30