forked from VerifyTests/DiffEngine
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessEx.cs
61 lines (57 loc) · 1.71 KB
/
ProcessEx.cs
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
static class ProcessEx
{
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
static extern SafeProcessHandle OpenProcess(int desiredAccess, bool inheritHandle, int processId);
const int processQueryInfo = 0x0400;
public static bool TryGet(int id, [NotNullWhen(true)] out Process? process)
{
using (var handle = OpenProcess(processQueryInfo, false, id))
{
if (handle.IsInvalid)
{
process = null;
return false;
}
}
try
{
process = Process.GetProcessById(id);
return true;
}
catch (ArgumentException)
{
// Handle Race condition if process doesnt exists
process = null;
return false;
}
}
public static void KillAndDispose(this Process process)
{
try
{
process.Kill();
var exited = process.WaitForExit(500);
if (!exited)
{
ExceptionHandler.Handle($"Failed to kill process. Id:{process.Id} Name: {process.MainModule?.FileName}");
}
}
catch (InvalidOperationException)
{
// Race condition can cause "No process is associated with this object"
}
catch (Win32Exception)
{
// no permission or already closed
// https://github.com/VerifyTests/DiffEngine/issues/542
}
catch (Exception exception)
{
ExceptionHandler.Handle($"Failed to kill process. Id:{process.Id} Name: {process.MainModule?.FileName}", exception);
}
finally
{
process.Dispose();
}
}
}