-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessWatcher.cs
More file actions
85 lines (72 loc) · 2.21 KB
/
Copy pathProcessWatcher.cs
File metadata and controls
85 lines (72 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace UiVisualDebugger;
public class ProcessWatcher : IDisposable
{
private readonly HashSet<int> _knownPids = new();
private CancellationTokenSource? _cts;
private Task? _watcherTask;
private readonly string _targetProcessName;
public event Action<Process>? ProcessStarted;
public bool IsEnabled { get; set; } = true;
public ProcessWatcher(string targetProcessName = "PhMeter.WpfApp")
{
_targetProcessName = targetProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
? System.IO.Path.GetFileNameWithoutExtension(targetProcessName)
: targetProcessName;
}
public void Start()
{
Stop();
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
foreach (var p in Process.GetProcessesByName(_targetProcessName))
{
_knownPids.Add(p.Id);
}
_watcherTask = Task.Run(() => WatchLoop(token), token);
}
public void Stop()
{
_cts?.Cancel();
_cts?.Dispose();
_cts = null;
_watcherTask = null;
}
private async Task WatchLoop(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (IsEnabled)
{
var currentProcs = Process.GetProcessesByName(_targetProcessName);
foreach (var proc in currentProcs)
{
if (!_knownPids.Contains(proc.Id))
{
_knownPids.Add(proc.Id);
ProcessStarted?.Invoke(proc);
}
}
_knownPids.RemoveWhere(pid =>
{
try { return Process.GetProcessById(pid).HasExited; }
catch { return true; }
});
}
}
catch { }
await Task.Delay(1000, token);
}
}
public void Dispose()
{
Stop();
}
}