无工作可做的 C# Windows 服务

标签 c# .net 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();
    }


}

}

事件日志条目

服务无法启动。 System.Security.SecurityException: 未找到来源,但无法搜索到部分或所有事件日志。不可访问的日志:安全。 在 System.Diagnostics.EventLog.FindSourceRegistration(字符串源、字符串机器名、 bool 只读) 在 System.Diagnostics.EventLog.SourceExists(字符串源,字符串机器名) 在 System.Diagnostics.EventLog.SourceExists(字符串源)

最佳答案

您需要启动一个前台线程 以防止进程退出。

这只能通过创建新线程来实现。 Timer 作为后台线程工作。 请参阅下面的更新!

在这里查看我的回答:

Best use of Windows Service for repeating a program call


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

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


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

     private void DoAlways()
     {
        while()
        {
           // ...
        }
     }

更新

System.Timers.Timer 类型的

Timer 使用 System.Threading.Timer,后者又使用 native WIN32 计时器。

我确实在我的机器 (XP) 上编译并安装了您的服务,它运行良好。服务启动没有问题。我建议您对 interval 值进行硬编码以查看它是否有效,因为我怀疑它的值为零,因此计时器从未初始化。

关于无工作可做的 C# Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5649442/

相关文章:

c# - 将 C# 应用程序移植到 Mono,需要使用 FirewallAPI。是否有等效的 Mono?

c# - 从内容页访问 MasterPage 上 UserControl 的属性

C#:在线检查实际日期?

wix - 如何让 WiX 删除 Windows 服务?

c# - 在数组中找到 FEW 最频繁的元素

c# - 如何使用 LINQ 选择*某些*项目?

c# - ASP.NET中如何从另一个网页调用一个网页

java - Windows 服务登录前访问网络

Python 服务自定义命令参数

c# - T Get<T>(int id) 和 T Get(int id) 的区别