使用DispatcherTimer和Windows服务

4

为什么我的DispatcherTimer在Windows服务中无法工作。

我想使用DispatcherTimer来检查Windows服务许可证。

    public OIMService()
    {
        InitializeComponent();
        _dispatcherTimer = new DispatcherTimer();
        if (!System.Diagnostics.EventLog.SourceExists("OIM_Log"))
        {
            EventLog.CreateEventSource("OIM_Log", "OIMLog");
        }
        EventLog.Source = "OIM_Log";
        EventLog.Log = "OIMLog";
        _helpers = new ValidationHelpers();
        StartTimer();

    }


protected override void OnStart(string[] args)
{
    System.Diagnostics.Debugger.Launch();

    if (_helpers.IsValid())
    {
        ConfigureServer();
        StartTimer();
    }
    else
    {
        this.Stop();
    }


}



 private void StartTimer()
        {
            const int time = 10;
            _dispatcherTimer.Tick += new EventHandler(DispatcherTimerTick);
            _dispatcherTimer.Interval = new TimeSpan(0, 0, Convert.ToInt32(time));
            _dispatcherTimer.IsEnabled = true;
            _dispatcherTimer.Start();
        }
    private void DispatcherTimerTick(object sender, EventArgs e)
    {

        EventLog.WriteEntry("test test test ...");
    }
1个回答

10
DispatcherTimer 的作用是在调度程序线程上触发其 Tick 事件。这很重要,因为您只能在调度程序线程上操作 Silverlight/WPF UI 元素。在 Windows 服务中,没有调度程序线程……也没有 UI 可以操作。为什么要使用 DispatcherTimer 而不是(比如)System.Timers.Timer

我想要使用DispatcherTimer每天检查Windows服务许可证。 - Tarek Saied
2
@tito11:为什么你认为在没有UI的情况下,DispatcherTimer是最适合使用的计时器? - Jon Skeet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接