私は wpf アプリケーション (MVVM なし) を持っています。このアプリケーションにはいくつかのバックグラウンド スレッド (特定の時間間隔で実行) が必要です。
これらのスレッドはアプリケーション レベルにある必要があります。つまり、ユーザーが任意の WPF ウィンドウを使用している場合、これらのスレッドはアクティブである必要があります。
基本的に、これらのスレッドは外部リソースを使用するため、ロックも必要です。
これを行う最善の方法を教えてください。
私は wpf アプリケーション (MVVM なし) を持っています。このアプリケーションにはいくつかのバックグラウンド スレッド (特定の時間間隔で実行) が必要です。
これらのスレッドはアプリケーション レベルにある必要があります。つまり、ユーザーが任意の WPF ウィンドウを使用している場合、これらのスレッドはアクティブである必要があります。
基本的に、これらのスレッドは外部リソースを使用するため、ロックも必要です。
これを行う最善の方法を教えてください。
WPF アプリケーションでアクションを定期的に実行する場合は、 DispatcherTimerクラスを使用できます。
コードを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
}
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();
}
これら 3 つのスレッドは 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();
}
}