winmr-api/Services/Scanners/ThreadScanner.cs

67 lines
2.5 KiB
C#
Raw Normal View History

2025-07-04 00:04:51 +03:00
/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2024-2025 Gregory Lirent */
2025-07-03 15:22:40 +03:00
using System.Diagnostics;
using WebmrAPI.Models;
using WebmrAPI.Utils;
namespace WebmrAPI.Services.Scanners
{
public class ThreadScanner : AbstractCpuScanner<ProcessThreadInfo>
{
override public ScanTarget Target { get => ScanTarget.Threads; }
internal int PID { get; private set; }
2025-07-03 20:01:19 +03:00
override internal async Task<bool> ScanAsync(Dictionary<long, ProcessThreadInfo> data)
2025-07-03 15:22:40 +03:00
{
2025-07-03 20:01:19 +03:00
return await Task.Run(() =>
2025-07-03 15:22:40 +03:00
{
2025-07-03 20:01:19 +03:00
try
2025-07-03 15:22:40 +03:00
{
2025-07-03 20:01:19 +03:00
using (var process = Process.GetProcessById(PID))
foreach (ProcessThread thread in process.Threads)
2025-07-03 15:22:40 +03:00
{
2025-07-03 20:01:19 +03:00
ProcessThreadInfo info;
if (GetFromCacheOrNew(thread.Id, out info))
{
info.CpuUsage = CalcCpuUsage(info.ProcessorTime, Container.Elapsed.TotalMilliseconds);
}
else
{
info.ID = thread.Id;
info.CpuUsage = 0;
}
2025-07-03 15:22:40 +03:00
2025-07-03 20:01:19 +03:00
info.BasePriority = thread.BasePriority;
info.CurrentPriority = thread.CurrentPriority;
info.TotalProcessorTime = thread.TotalProcessorTime;
2025-07-03 15:22:40 +03:00
2025-07-03 20:01:19 +03:00
data.Add(info.ID, info);
}
return true;
}
catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 5)
{
Provider.Logger.LogWarning($"Access denied to process {PID} for thread scanning. Error: {ex.Message}");
}
catch (InvalidOperationException ex)
{
Provider.Logger.LogWarning($"Process {PID} might have exited during thread enumeration. Error: {ex.Message}");
}
catch (Exception ex)
{
Provider.Logger.LogError($"An unexpected error occurred while scanning threads for PID {PID}. Error: {ex.Message}");
2025-07-03 15:22:40 +03:00
}
return false;
2025-07-03 20:01:19 +03:00
});
2025-07-03 15:22:40 +03:00
}
public ThreadScanner(IScanProvider scanner, LazyConcurrentContainer<ProcessThreadInfo> container, int pid)
: base(scanner, container)
{
PID = pid;
}
}
}