将DispatcherTimer与Windows服务一起使用

Tar*_*ied 4 c# windows-services dispatcher

为什么我的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 ...");
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

重点DispatcherTimerTick在调度程序线程上触发它的事件.这很重要,因为您只能在调度程序线程上操作Silverlight/WPF UI元素.在Windows服务,也就是没有分派线程...有没有UI操控.你为什么要用DispatcherTimer而不是(比如说)System.Timers.Timer

  • @ tito11:当你没有UI时,为什么你认为DispatcherTimer是最合适的计时器? (2认同)