【问题标题】:Dispatcher Timer fires while project stopped项目停止时调度程序计时器触发
【发布时间】:2025-12-07 18:00:02
【问题描述】:

我有一个 VS 2012 项目,它有一个计时器,每 2 分钟启动一个进程。它工作正常,但似乎在项目停止后继续运行。我所拥有的唯一迹象是它以计时器间隔将错误记录到数据库中。我需要明确停止计时器吗?当您按下停止按钮时,它是如何完成的?当我关闭项目时,日志记录会停止。

tick 事件 (RefreshBroadcast) 静默失败(当应用程序未运行时),但日志记录工作正常,而且日志记录表明它无权访问配置文件,因为它使用默认值(用于应用程序名称等) .日志记录代码也应该在视图中显示错误,所以最终 Visual Studio 会告诉我我的错误视图窗口“没有由...识别的资源”。这将在项目停止时发生,而我正在其他地方编码。在此之后,停止记录到数据库。

 Public Sub New()
        If Not System.Windows.Application.Current.MainWindow Is Nothing Then
            _refreshBroadcastTimer = New System.Windows.Threading.DispatcherTimer()
            AddHandler _refreshBroadcastTimer.Tick, AddressOf dispatcherTimer_Tick
            If Debugger.IsAttached Then
                _refreshBroadcastTimer.Interval = New TimeSpan(0, 0, 30)
            Else
                _refreshBroadcastTimer.Interval = New TimeSpan(0, 0, My.Settings.RefreshBroadcastIntervalMinutes * 60) ' change to seconds
            End If
            _refreshBroadcastTimer.Start()
        End If
    End Sub




Private Sub dispatcherTimer_Tick(sender As Object, e As EventArgs)
    Try
        RefreshBroadcast()
    Catch ex As Exception
        LogException(ex)
    End Try
End Sub

【问题讨论】:

    标签: .net wpf vb.net


    【解决方案1】:

    有趣的是,问一个问题通常会给你答案,这已经困扰了我好几天了,但我想我已经明白了。因为我在更新视图模型时启动了计时器,所以每当我在编辑器中打开视图时,它都会在后台创建视图模型的一个实例,这会启动计时器。我想我必须包装代码,这样它就不会在设计器中触发。

    我已将初始化代码包装在

     If Not System.ComponentModel.DesignerProperties.GetIsInDesignMode(New DependencyObject()) Then
    

    目前看来效果不错。

    【讨论】: