C#Windows服务没有工作要做

Nic*_*ray 3 .net c# windows-services

我创建了一个C#windows服务,应该发送一些电子邮件,但是当我启动服务时,我收到消息'本地服务开始然后停止'......'如果他们没有工作可以自动停止某些服务'

为什么会这样?

namespace EmailService
{
public partial class EmailService : ServiceBase
{
    private System.Timers.Timer _timer = null;
    private DateTime _lastRun = DateTime.Now;
    private int _timerIntervalValue;

    public EmailService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {

        if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Timer"]))
        {
            throw new Exception("The timer value is not set in the app.config.");
        }
        else
        {
            _timerIntervalValue = Convert.ToInt32(ConfigurationManager.AppSettings["Timer"]);
        }

        _timer = new System.Timers.Timer(_timerIntervalValue);
        _timer.Elapsed += OnTimedEvent;
        _timer.Interval = Convert.ToInt32(_timerIntervalValue);
        _timer.Enabled = true;

    }

    protected override void OnStop()
    {
        _timer.Stop();
        _timer.Dispose();
    }

    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Email email = new Email();
        email.ProcessEmails();
        _lastRun = DateTime.Now;
        _timer.Start();
    }


}

}
Run Code Online (Sandbox Code Playgroud)

事件日志条目

服务无法启动.System.Security.SecurityException:找不到源,但无法搜索部分或全部事件日志.无法访问的日志:安全性.System.Diagnostics.EventLog.SourceExists处于System.Diagnostics.EventLog.FindSourceRegistration(String source,String machineName,Boolean readOnly),位于System.Diagnostics.EventLog.SourceExists(String source)的System.Diagnostics.EventLog.SourceExists(String source,String machineName)

Ali*_*tad 6

您需要启动Foreground线程以防止进程退出.

这只能通过创建新的Thread来实现. A Timer作为后台线程.见下面的更新!

在这里看到我的答案:

最好使用Windows服务重复程序调用


这是一种非常简单的方法:

public partial class EmailService : ServiceBase
{
    Thread _thread = new Thread(DoAlways)


     protected override void OnStart(string[] args)
     {
        _thread.Start();
     }

     private void DoAlways()
     {
        while()
        {
           // ...
        }
     }
Run Code Online (Sandbox Code Playgroud)

UPDATE

Timer一种类型System.Timers.Timer使用System.Threading.Timer,而后者又使用本机WIN32计时器.

我确实在我的机器(XP)上编译和安装了你的服务,它只是起作用了.服务开始没有问题.我建议你硬编码间隔值,看它是否有效,因为我怀疑它的值为零因此计时器从未初始化.