LogService.cs
1.4 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
namespace IndustrialControl.Services;
public class LogService : IDisposable
{
private readonly string _logsDir = Path.Combine(FileSystem.AppDataDirectory, "logs");
private readonly TimeSpan _interval = TimeSpan.FromMilliseconds(800);
private CancellationTokenSource? _cts;
public event Action<string>? LogTextUpdated;
public string TodayLogPath => Path.Combine(_logsDir, $"gr-{DateTime.Now:yyyy-MM-dd}.txt");
public void Start()
{
Stop();
_cts = new CancellationTokenSource();
_ = Task.Run(() => LoopAsync(_cts.Token));
}
public void Stop()
{
_cts?.Cancel();
_cts?.Dispose();
_cts = null;
}
private async Task LoopAsync(CancellationToken token)
{
Directory.CreateDirectory(_logsDir);
string last = string.Empty;
while (!token.IsCancellationRequested)
{
try
{
if (File.Exists(TodayLogPath))
{
var text = await File.ReadAllTextAsync(TodayLogPath, token);
if (!string.Equals(text, last, StringComparison.Ordinal))
{
last = text;
LogTextUpdated?.Invoke(text);
}
}
}
catch { }
await Task.Delay(_interval, token);
}
}
public void Dispose() => Stop();
}