Zzz – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Threading;
5 using System.Threading.Tasks;
6 using Serilog;
7 using Zzz.Properties;
8 using Zzz.Utilities;
9  
10 namespace Zzz.Idle
11 {
12 public class WindowPresence : IDisposable
13 {
14 #region Public Events & Delegates
15  
16 public event EventHandler<EventArgs> WindowDetected;
17  
18 #endregion
19  
20 #region Private Delegates, Events, Enums, Properties, Indexers and Fields
21  
22 private readonly CancellationToken _cancellationToken;
23  
24 private readonly Task _scanTask;
25  
26 private CancellationTokenSource _cancellationTokenSource;
27 private Configuration.Configuration _configuration;
28  
29 #endregion
30  
31 #region Constructors, Destructors and Finalizers
32  
33 public WindowPresence(Configuration.Configuration configuration) : this()
34 {
35 _configuration = configuration;
36 }
37  
38 private WindowPresence()
39 {
40 _cancellationTokenSource = new CancellationTokenSource();
41 _cancellationToken = _cancellationTokenSource.Token;
42  
43 _scanTask = Scan(_cancellationToken);
44 }
45  
46 public void Dispose()
47 {
48 _cancellationTokenSource?.Cancel();
49  
50 _scanTask.Wait(CancellationToken.None);
51  
52 _cancellationTokenSource = null;
53 }
54  
55 #endregion
56  
57 #region Private Methods
58  
59 private async Task Scan(CancellationToken cancellationToken)
60 {
61 try
62 {
63 do
64 {
65 try
66 {
67 await Task.Delay(TimeSpan.FromMinutes((int) _configuration.Timeout), cancellationToken);
68  
69 foreach (var title in RefreshWindows())
70 {
71 if (!_configuration.WindowsWatchList.Contains(title))
72 {
73 continue;
74 }
75  
76 WindowDetected?.Invoke(this, EventArgs.Empty);
77 }
78 }
79 catch (Exception ex)
80 {
81 Log.Warning(ex, "Window scan failure.");
82 }
83 } while (!cancellationToken.IsCancellationRequested);
84 }
85 catch (Exception ex)
86 {
87 Log.Warning(ex, "Window scan thread terminated.");
88 }
89 }
90  
91 private static IEnumerable<string> RefreshWindows()
92 {
93 return Helpers.FindWindows((window, param) => true).Select(Helpers.GetWindowTitle)
94 .Where(title => !string.IsNullOrEmpty(title));
95 }
96  
97 #endregion
98 }
99 }