-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBoundedCleanup.cs
More file actions
55 lines (48 loc) · 1.8 KB
/
BoundedCleanup.cs
File metadata and controls
55 lines (48 loc) · 1.8 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
namespace DotPilot.UITests;
internal static class BoundedCleanup
{
private const string CleanupFailureMessagePrefix = "Cleanup for '";
private const string CleanupFailureMessageSuffix = "' failed.";
private const string CleanupThreadNamePrefix = "DotPilot.UITests cleanup: ";
private const string CleanupTimeoutMessagePrefix = "Timed out while waiting for '";
private const string CleanupTimeoutMessageMiddle = "' cleanup to finish within ";
private const string CleanupTimeoutMessageSuffix = ".";
public static void Run(Action cleanupAction, TimeSpan timeout, string operationName)
{
ArgumentNullException.ThrowIfNull(cleanupAction);
ArgumentException.ThrowIfNullOrWhiteSpace(operationName);
using var cleanupCompleted = new ManualResetEventSlim(false);
Exception? cleanupException = null;
var cleanupThread = new Thread(() =>
{
try
{
cleanupAction();
}
catch (Exception exception)
{
cleanupException = exception;
}
finally
{
cleanupCompleted.Set();
}
})
{
IsBackground = true,
Name = $"{CleanupThreadNamePrefix}{operationName}",
};
cleanupThread.Start();
if (!cleanupCompleted.Wait(timeout))
{
throw new TimeoutException(
$"{CleanupTimeoutMessagePrefix}{operationName}{CleanupTimeoutMessageMiddle}{timeout}{CleanupTimeoutMessageSuffix}");
}
if (cleanupException is not null)
{
throw new InvalidOperationException(
$"{CleanupFailureMessagePrefix}{operationName}{CleanupFailureMessageSuffix}",
cleanupException);
}
}
}