diff --git a/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs b/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs index 7457ae5..206efb9 100644 --- a/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs +++ b/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs @@ -1,4 +1,4 @@ -using hass_workstation_service.Communication; +using hass_workstation_service.Communication; using Serilog; using Serilog.Core; using System; @@ -73,26 +73,33 @@ namespace hass_workstation_service.Domain.Sensors .Select(p => p.Id.ToString()) .ToHashSet(); var REprocessid = new Regex(@"(?<=Handle="").*?(?="")", RegexOptions.Compiled); - - var numberOfLogonSessionsWithExplorer = new ManagementObjectSearcher(scope, new SelectQuery("SELECT * FROM Win32_SessionProcess")).Get() - .Cast() - .Where(mo => explorerProcesses.Contains(REprocessid.Match(mo["Dependent"].ToString()).Value)) - .Select(mo => mo["Antecedent"].ToString()) - .Distinct() - .Count(); + int numberOfLogonSessionsWithExplorer = 1; + using (var managemntObjectSearcher = new ManagementObjectSearcher(scope, new SelectQuery("SELECT * FROM Win32_SessionProcess"))) + { + numberOfLogonSessionsWithExplorer = managemntObjectSearcher.Get() + .Cast() + .Where(mo => explorerProcesses.Contains(REprocessid.Match(mo["Dependent"].ToString()).Value)) + .Select(mo => mo["Antecedent"].ToString()) + .Distinct() + .Count(); + } int numberOfUserDesktops = 1; // this can fail sometimes, that's why we set numberOfUserDesktops to 1 try { - numberOfUserDesktops = new ManagementObjectSearcher(scope, new SelectQuery("select * from win32_Perfrawdata_TermService_TerminalServicesSession")).Get().Count - 1; // don't count Service desktop + using (var managementObjectSearcher = new ManagementObjectSearcher(scope, new SelectQuery("select * from win32_Perfrawdata_TermService_TerminalServicesSession"))) + { + + numberOfUserDesktops = managementObjectSearcher.Get().Count - 1; // don't count Service desktop + } } catch { - + } - + var numberOflogonUIProcesses = Process.GetProcessesByName("LogonUI").Length; @@ -104,7 +111,9 @@ namespace hass_workstation_service.Domain.Sensors return PCUserStatuses.LoggedOff; } else + { return PCUserStatuses.InUse; + } } catch (Exception e) {