64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using System.Diagnostics;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Moonlight.Api.Helpers;
|
|
|
|
namespace Moonlight.Api.Services;
|
|
|
|
public class ApplicationService : IHostedLifecycleService
|
|
{
|
|
public DateTimeOffset StartedAt { get; private set; }
|
|
public string VersionName { get; private set; } = "N/A";
|
|
public bool IsUpToDate { get; set; } = true;
|
|
public string OperatingSystem { get; private set; } = "N/A";
|
|
|
|
public Task<long> GetMemoryUsageAsync()
|
|
{
|
|
using var currentProcess = Process.GetCurrentProcess();
|
|
return Task.FromResult(currentProcess.WorkingSet64);
|
|
}
|
|
|
|
public async Task<double> GetCpuUsageAsync()
|
|
{
|
|
using var currentProcess = Process.GetCurrentProcess();
|
|
|
|
// Get initial values
|
|
var startCpuTime = currentProcess.TotalProcessorTime;
|
|
var startTime = DateTime.UtcNow;
|
|
|
|
// Wait a bit to calculate the diff
|
|
await Task.Delay(500);
|
|
|
|
// New values
|
|
var endCpuTime = currentProcess.TotalProcessorTime;
|
|
var endTime = DateTime.UtcNow;
|
|
|
|
// Calculate CPU usage
|
|
var cpuUsedMs = (endCpuTime - startCpuTime).TotalMilliseconds;
|
|
var totalMsPassed = (endTime - startTime).TotalMilliseconds;
|
|
var cpuUsagePercent = (cpuUsedMs / (Environment.ProcessorCount * totalMsPassed)) * 100;
|
|
|
|
return Math.Round(cpuUsagePercent, 2);
|
|
}
|
|
|
|
public async Task StartedAsync(CancellationToken cancellationToken)
|
|
{
|
|
StartedAt = DateTimeOffset.UtcNow;
|
|
|
|
// TODO: Update / version check
|
|
|
|
VersionName = "v2.1.0 (a2d4edc0e5)";
|
|
IsUpToDate = true;
|
|
|
|
OperatingSystem = OsHelper.GetName();
|
|
}
|
|
|
|
#region Unused
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
public Task StartingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
|
|
#endregion
|
|
} |