ContextWindow: Change renew context event handling

This commit is contained in:
2023-09-18 21:46:14 +02:00
parent a6fef7fd9b
commit 3a73265a75
7 changed files with 44 additions and 32 deletions

View File

@ -7,30 +7,32 @@ using System.Windows.Threading;
namespace Elwig.Windows {
public abstract class ContextWindow : Window {
public static readonly int RenewSec = 10;
protected AppDbContext Context { get; private set; }
protected bool LockContext { get; set; } = false;
private readonly DispatcherTimer ContextRenewTimer;
private static readonly int ContextRenewSec = 10;
private readonly DispatcherTimer _timer;
private bool _renewPending = false;
public ContextWindow() : base() {
ContextRenewTimer = new DispatcherTimer();
ContextRenewTimer.Tick += new EventHandler(OnRenewContext);
ContextRenewTimer.Interval = new TimeSpan(0, 0, ContextRenewSec);
ContextRenewTimer.Start();
_timer = new DispatcherTimer();
_timer.Tick += new EventHandler(OnShouldRenewContext);
_timer.Interval = new TimeSpan(0, 0, RenewSec);
_timer.Start();
Context = new();
Loaded += OnLoaded;
}
private void OnRenewContext(object? sender, EventArgs evt) {
if (LockContext || !Context.HasBackendChanged) return;
Context.Dispose();
Context = new();
RenewContext().GetAwaiter().GetResult();
private async void OnShouldRenewContext(object? sender, EventArgs evt) {
if (!Context.HasBackendChanged) return;
_renewPending = true;
if (LockContext) return;
await RenewContext();
}
private void OnLoaded(object sender, RoutedEventArgs evt) {
RenewContext().GetAwaiter().GetResult();
OnRenewContext().GetAwaiter().GetResult();
}
protected override void OnClosed(EventArgs evt) {
@ -38,6 +40,14 @@ namespace Elwig.Windows {
Context.Dispose();
}
abstract protected Task RenewContext();
protected async Task RenewContext() {
if (!_renewPending) return;
Context.Dispose();
Context = new();
await OnRenewContext();
_renewPending = false;
}
abstract protected Task OnRenewContext();
}
}