Jeetendra.Sharma
Jeetendra.Sharma

Reputation: 194

BackGround Thread with timer for application level-WPF Application

I have a wpf application(No MVVM), this application requires several background thread(Runs with specific time interval).

These thread should be on Application Level i.e. if user is on any WPF Window, these threads should be active.

Basically these thread will are using external resources so locking is also required.

Kindly tell me the best way to do this.

Upvotes: 3

Views: 5792

Answers (2)

Jeetendra.Sharma
Jeetendra.Sharma

Reputation: 194

 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();
    }

These three threads a intialized on 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();
        }

    }

Upvotes: 2

Tudor
Tudor

Reputation: 62439

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

Put your code as the handler of the Tick event and set the Interval property to whatever you need. Something like:

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
}

Upvotes: 8

Related Questions