-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathFileQueue.cs
More file actions
74 lines (59 loc) · 1.8 KB
/
FileQueue.cs
File metadata and controls
74 lines (59 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace TensorStack.Common.Common
{
public static class FileQueue
{
private static readonly ConcurrentQueue<(string path, int retries)> _queue = new();
private static readonly SemaphoreSlim _signal = new(0);
private static readonly CancellationTokenSource _cts = new();
private const int MaxRetries = 5;
private const int RetryDelayMs = 500;
static FileQueue()
{
Task.Run(Worker);
}
public static void Delete(string path)
{
_queue.Enqueue((path, 0));
_signal.Release();
}
private static async Task Worker()
{
while (!_cts.IsCancellationRequested)
{
await _signal.WaitAsync(_cts.Token);
if (!_queue.TryDequeue(out var item))
continue;
if (TryDelete(item.path))
continue;
if (item.retries < MaxRetries)
{
await Task.Delay(RetryDelayMs);
_queue.Enqueue((item.path, item.retries + 1));
_signal.Release();
}
}
}
private static bool TryDelete(string filename)
{
try
{
if (!File.Exists(filename))
return true;
File.Delete(filename);
return true;
}
catch (IOException) { return false; }
catch (UnauthorizedAccessException) { return false; }
}
public static void Shutdown()
{
_cts.Cancel();
_signal.Release();
}
}
}