BradleyUffner

non-blocking async

Jun 21st, 2018
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Data;
  11. using System.Windows.Documents;
  12. using System.Windows.Input;
  13. using System.Windows.Media;
  14. using System.Windows.Media.Imaging;
  15. using System.Windows.Navigation;
  16. using System.Windows.Shapes;
  17.  
  18. namespace asyncTest
  19. {
  20.     public partial class MainWindow : Window
  21.     {
  22.         public MainWindow()
  23.         {
  24.             InitializeComponent();
  25.         }
  26.  
  27.         private async void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
  28.         {
  29.             var cts = new CancellationTokenSource();
  30.             Closing += delegate { cts.Cancel(); };
  31.             await CheckToClose(cts.Token);
  32.         }
  33.  
  34.         public async Task CheckToClose(CancellationToken ct)
  35.         {
  36.             while (!ct.IsCancellationRequested)
  37.             {
  38.                 try
  39.                 {
  40.                     await Task.Delay(TimeSpan.FromSeconds(1), ct);
  41.                 }
  42.                 catch (TaskCanceledException)
  43.                 {
  44.                     return;
  45.                 }
  46.  
  47.                 Debug.WriteLine("checking DB");
  48.                 var keepRunning = !await ShouldKeepRunning(ct);
  49.                 if (!keepRunning)
  50.                 {
  51.                     Close();
  52.                     return;
  53.                 }
  54.             }
  55.         }
  56.  
  57.         public async Task<bool> ShouldKeepRunning(CancellationToken ct)
  58.         {
  59.             await Task.Delay(TimeSpan.FromSeconds(5)); // simulate a long running db task
  60.             return chkAllowClose.IsChecked.GetValueOrDefault(false);
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment