BackGround Thread with Timer for Application Level - WPF Application

I have a wpf application (no MVVM), this application requires several background threads (runs with a certain time interval).

These threads must be at the application level, i.e. if the user is in any WPF window, these threads must be active.

Basically, these threads will use external resources, so locking is required.

Please tell me the best way to do this.

+3
source share
2 answers

If you want to periodically perform an action in a WPF application, you can use the DispatcherTimer class .

Tick Interval , . - :

DispatcherTimer dt = new DispatcherTimer();
dt.Tick += new EventHandler(timer_Tick);
dt.Interval = new TimeSpan(1, 0, 0); // execute every hour
dt.Start();

// Tick handler    
private void timer_Tick(object sender, EventArgs e)
{
    // code to execute periodically
}
+8
 private void InitializeDatabaseConnectionCheckTimer()
    {
        DispatcherTimer _timerNet = new DispatcherTimer();
        _timerNet.Tick += new EventHandler(DatabaseConectionCheckTimer_Tick);
        _timerNet.Interval = new TimeSpan(_batchScheduleInterval);
        _timerNet.Start();
    }
    private void InitializeApplicationSyncTimer()
    {
        DispatcherTimer _timer = new DispatcherTimer();
        _timer.Tick += new EventHandler(AppSyncTimer_Tick);
        _timer.Interval = new TimeSpan(_batchScheduleInterval);
        _timer.Start();
    }

    private void IntializeImageSyncTimer()
    {
        DispatcherTimer _imageTimer = new DispatcherTimer();
        _imageTimer.Tick += delegate
        {
            lock (this)
            {
                ImagesSync.SyncImages();
            }
        };
        _imageTimer.Interval = new TimeSpan(_batchScheduleInterval);
        _imageTimer.Start();
    }

App_OnStart

protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        try
        {
            _batchScheduleInterval = Convert.ToInt32(ApplicationConfigurationManager.Properties["BatchScheduleInterval"]);
        }
        catch(InvalidCastException err)
        {
            TextLogger.Log(err.Message);
        }

        Helper.SaveKioskApplicationStatusLog(Constant.APP_START);
        if (SessionManager.Instance.DriverId == null && _batchScheduleInterval!=0)
        {
            InitializeApplicationSyncTimer();
            InitializeDatabaseConnectionCheckTimer();
            IntializeImageSyncTimer();
        }

    }
+1

All Articles