-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatchProcessor.cs
More file actions
65 lines (57 loc) · 2.12 KB
/
Copy pathBatchProcessor.cs
File metadata and controls
65 lines (57 loc) · 2.12 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DropResize
{
public class BatchProcessor
{
private readonly ImageResizeService resizeService;
public BatchProcessor(ImageResizeService resizeService)
{
this.resizeService = resizeService;
}
public async Task ProcessAsync(
IEnumerable<string> inputFiles,
ResizeProfile profile,
string outputFolder,
int workerCount,
CancellationToken cancellationToken,
Action<ResizeResult> resultReceived,
Action<int, int> progressChanged)
{
var queue = new ConcurrentQueue<string>(inputFiles);
var total = queue.Count;
var completed = 0;
var workers = new List<Task>();
var actualWorkerCount = Math.Max(1, workerCount);
for (var i = 0; i < actualWorkerCount; i++)
{
workers.Add(Task.Run(() =>
{
var originalPriority = Thread.CurrentThread.Priority;
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
try
{
string inputPath;
while (queue.TryDequeue(out inputPath))
{
cancellationToken.ThrowIfCancellationRequested();
var result = resizeService.Process(new ResizeJob(inputPath, profile, outputFolder));
resultReceived(result);
var done = Interlocked.Increment(ref completed);
progressChanged(done, total);
Thread.Sleep(1);
}
}
finally
{
Thread.CurrentThread.Priority = originalPriority;
}
}, cancellationToken));
}
await Task.WhenAll(workers);
}
}
}