Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- namespace asyncTest
- {
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- }
- private async void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
- {
- var cts = new CancellationTokenSource();
- Closing += delegate { cts.Cancel(); };
- await CheckToClose(cts.Token);
- }
- public async Task CheckToClose(CancellationToken ct)
- {
- while (!ct.IsCancellationRequested)
- {
- try
- {
- await Task.Delay(TimeSpan.FromSeconds(1), ct);
- }
- catch (TaskCanceledException)
- {
- return;
- }
- Debug.WriteLine("checking DB");
- var keepRunning = !await ShouldKeepRunning(ct);
- if (!keepRunning)
- {
- Close();
- return;
- }
- }
- }
- public async Task<bool> ShouldKeepRunning(CancellationToken ct)
- {
- await Task.Delay(TimeSpan.FromSeconds(5)); // simulate a long running db task
- return chkAllowClose.IsChecked.GetValueOrDefault(false);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment