Portable Tool for an Ideal Windows Setup
C# activatorbloatware-removalcsharpdebloatdebloaterdisable-servicesmonitoring-systemportableprivacy-toolsregistry-tweakssystem-tuningsystem-utilitytelemetrytweakerwindows-10windows-11windows-debloatwindows-defenderwindows-optimizationwindows-tweaks
add handling for selecting only existing tasks and fix background processing
Greedeksb574027508be
diff --git a/.Source/GTweak/Utilities/Configuration/MonitoringService.cs b/.Source/GTweak/Utilities/Configuration/MonitoringService.csindex 7688ed8f..53ff575e 100644--- a/.Source/GTweak/Utilities/Configuration/MonitoringService.cs+++ b/.Source/GTweak/Utilities/Configuration/MonitoringService.cs@@ -5,7 +5,6 @@ using System.Diagnostics;using System.Management;using System.Runtime.InteropServices;using System.ServiceProcess;-using System.Threading;using System.Threading.Tasks;namespace GTweak.Utilities.Configuration@@ -14,7 +13,7 @@ namespace GTweak.Utilities.Configuration{internal event Action<DeviceType> HandleDevicesEvents;private readonly List<ManagementEventWatcher> _eventWatchers = new List<ManagementEventWatcher>();- private static readonly ServiceController[] _servicesList = ServiceController.GetServices();+ private readonly ServiceController[] _servicesList = ServiceController.GetServices();internal string GetNumberRunningProcesses => GetProcessCount().Result;internal string GetNumberRunningService => GetServicesCount().Result;@@ -62,9 +61,9 @@ namespace GTweak.Utilities.Configurationprivate static extern bool GetSystemTimes(out SystemTime lpIdleTime, out SystemTime lpKernelTime, out SystemTime lpUserTime);- private static Task<string> GetProcessCount()+ private async Task<string> GetProcessCount(){- return Task.Run(() =>+ return await Task.Run(() =>{uint capacity = 1024;@@ -90,12 +89,12 @@ namespace GTweak.Utilities.Configuration}return Process.GetProcesses().Length.ToString();- });+ }).ConfigureAwait(false);}- private static Task<string> GetServicesCount()+ private async Task<string> GetServicesCount(){- return Task.Run(() =>+ return await Task.Run(() =>{int running = 0;Parallel.ForEach(_servicesList, svc =>@@ -104,17 +103,17 @@ namespace GTweak.Utilities.Configuration{svc.Refresh();if (svc.Status == ServiceControllerStatus.Running)- Interlocked.Increment(ref running);+ running++;}catch (Exception ex) { ErrorLogging.LogDebug(ex); }});return running.ToString();- });+ }).ConfigureAwait(false);}- private static Task<int> GetPhysicalAvailableMemory()+ private async Task<int> GetPhysicalAvailableMemory(){- return Task.Run(() =>+ return await Task.Run(() =>{MemoryStatus memStatus = new MemoryStatus();if (!GlobalMemoryStatusEx(memStatus))@@ -123,7 +122,7 @@ namespace GTweak.Utilities.Configurationint totalMemory = (int)(memStatus.ullTotalPhys / 1048576);int availableMemory = (int)(memStatus.ullAvailPhys / 1048576);return (int)((float)(totalMemory - availableMemory) / totalMemory * 100);- });+ }).ConfigureAwait(false);}internal async Task GetTotalProcessorUsage()@@ -161,26 +160,26 @@ namespace GTweak.Utilities.Configurationinternal void StartDeviceMonitoring(){- Task.Run(() =>- {- if (SystemDiagnostics.isMsftAvailable)- SubscribeToDeviceEvents($"TargetInstance ISA 'MSFT_PhysicalDisk'", DeviceType.Storage, @"root\Microsoft\Windows\Storage");- else- SubscribeToDeviceEvents($"TargetInstance ISA 'Win32_DiskDrive'", DeviceType.Storage);- SubscribeToDeviceEvents("TargetInstance ISA 'Win32_SoundDevice'", DeviceType.Audio);- SubscribeToDeviceEvents("TargetInstance ISA 'Win32_NetworkAdapter' AND TargetInstance.NetConnectionStatus IS NOT NULL", DeviceType.Network);- }).ConfigureAwait(false);+ if (SystemDiagnostics.isMsftAvailable)+ SubscribeToDeviceEvents($"TargetInstance ISA 'MSFT_PhysicalDisk'", DeviceType.Storage, @"root\Microsoft\Windows\Storage");+ else+ SubscribeToDeviceEvents($"TargetInstance ISA 'Win32_DiskDrive'", DeviceType.Storage);+ SubscribeToDeviceEvents("TargetInstance ISA 'Win32_SoundDevice'", DeviceType.Audio);+ SubscribeToDeviceEvents("TargetInstance ISA 'Win32_NetworkAdapter' AND TargetInstance.NetConnectionStatus IS NOT NULL", DeviceType.Network);}private void SubscribeToDeviceEvents(string filter, DeviceType type, string scope = @"root\CIMV2"){try{- WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent", TimeSpan.FromSeconds(1), filter);- ManagementEventWatcher managementEvent = new ManagementEventWatcher(new ManagementScope(scope), query);- managementEvent.EventArrived += (s, e) => { HandleDevicesEvents?.Invoke(type); };- managementEvent.Start();- _eventWatchers.Add(managementEvent);+ Task.Run(() =>+ {+ WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent", TimeSpan.FromSeconds(1), filter);+ ManagementEventWatcher managementEvent = new ManagementEventWatcher(new ManagementScope(scope), query);+ managementEvent.EventArrived += (s, e) => { HandleDevicesEvents?.Invoke(type); };+ managementEvent.Start();+ _eventWatchers.Add(managementEvent);+ });}catch (Exception ex) { ErrorLogging.LogDebug(ex); }}@@ -200,7 +199,7 @@ namespace GTweak.Utilities.Configurationcatch (Exception ex) { ErrorLogging.LogDebug(ex); }}_eventWatchers.Clear();- }).ConfigureAwait(false);+ });}}}diff --git a/.Source/GTweak/Utilities/Configuration/SystemDiagnostics.cs b/.Source/GTweak/Utilities/Configuration/SystemDiagnostics.csindex 5521317d..88d08660 100644--- a/.Source/GTweak/Utilities/Configuration/SystemDiagnostics.cs+++ b/.Source/GTweak/Utilities/Configuration/SystemDiagnostics.cs@@ -104,23 +104,27 @@ namespace GTweak.Utilities.Configurationinternal void GetHardwareData(){- try+ Parallel.Invoke(() =>{- using var managementObj = new ManagementObjectSearcher(@"root\microsoft\windows\storage", "select FriendlyName from MSFT_PhysicalDisk", new EnumerationOptions { ReturnImmediately = true });- var results = managementObj.Get();- isMsftAvailable = results != null && results.Count > 0;- }- catch { isMsftAvailable = false; }+ try+ {+ using var managementObj = new ManagementObjectSearcher(@"root\microsoft\windows\storage", "select FriendlyName from MSFT_PhysicalDisk", new EnumerationOptions { ReturnImmediately = true });+ var results = managementObj.Get();+ isMsftAvailable = results != null && results.Count > 0;+ }+ catch { isMsftAvailable = false; }+ });Parallel.Invoke(GetBiosInfo,GetMotherboardInfo,GetProcessorInfo,- GeVideoInfo,+ GetGraphicsInfo,GetMemoryInfo,- GetUserIpAddress,- () => { UpdatingDevicesData(); }+ GetUserIpAddress);++ UpdatingDevicesData();}internal void UpdatingDevicesData(DeviceType deviceType = DeviceType.All)@@ -216,7 +220,7 @@ namespace GTweak.Utilities.Configuration/// The maximum video card memory that can be obtained via WMI is 4 GB. Therefore, the memory size is obtained from the registry./// For discrete video cards or older models, the parameters will have the REG_BINARY type, and for integrated ones, REG_SZ./// </summary>- private void GeVideoInfo()+ private void GetGraphicsInfo(){static (bool, string, string) GetMemorySize(string name){diff --git a/.Source/GTweak/Utilities/Managers/TaskSchedulerManager.cs b/.Source/GTweak/Utilities/Managers/TaskSchedulerManager.csindex 350f3234..57262ce6 100644--- a/.Source/GTweak/Utilities/Managers/TaskSchedulerManager.cs+++ b/.Source/GTweak/Utilities/Managers/TaskSchedulerManager.cs@@ -2,6 +2,7 @@using GTweak.Utilities.Helpers;using GTweak.Utilities.Storage;using System;+using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;@@ -13,10 +14,15 @@ namespace GTweak.Utilities.Managers{internal static bool IsTaskEnabled(params string[] tasklist){+ string[] existingTasks = GetExistingTasks(tasklist);++ if (existingTasks.Length == 0)+ return false;+byte numberRunningTask = 0;using (Microsoft.Win32.TaskScheduler.TaskService taskService = new Microsoft.Win32.TaskScheduler.TaskService()){- numberRunningTask += (byte)(from string taskname in tasklist+ numberRunningTask += (byte)(from string taskname in existingTaskslet task = taskService.GetTask(taskname)where task != nullwhere task.Enabled@@ -29,8 +35,13 @@ namespace GTweak.Utilities.Managers{Task.Run(delegate{+ string[] existingTasks = GetExistingTasks(tasklist);++ if (existingTasks.Length == 0)+ return;+using Microsoft.Win32.TaskScheduler.TaskService taskService = new Microsoft.Win32.TaskScheduler.TaskService();- foreach (string taskname in tasklist)+ foreach (string taskname in existingTasks){using Microsoft.Win32.TaskScheduler.Task task = taskService.GetTask(taskname);if (task != null && task.Enabled != state)@@ -46,8 +57,13 @@ namespace GTweak.Utilities.Managers{Task.Run(delegate{+ string[] existingTasks = GetExistingTasks(tasklist);++ if (existingTasks.Length == 0)+ return;+StringBuilder sb = new StringBuilder();- foreach (string task in tasklist)+ foreach (string task in existingTasks)sb.Append($"schtasks /change {(state ? "/enable" : "/disable")} /tn \"{task}\" & ");string tasksCommand = sb.ToString().TrimEnd(' ', '&');@@ -60,8 +76,13 @@ namespace GTweak.Utilities.Managers{Task.Run(delegate{+ string[] existingTasks = GetExistingTasks(tasklist);++ if (existingTasks.Length == 0)+ return;+using Microsoft.Win32.TaskScheduler.TaskService taskService = new Microsoft.Win32.TaskScheduler.TaskService();- foreach (string taskname in tasklist)+ foreach (string taskname in existingTasks){Microsoft.Win32.TaskScheduler.Task task = taskService.GetTask(taskname);if (task != null)@@ -80,5 +101,18 @@ namespace GTweak.Utilities.Managerselsereturn partialName;}++ private static string[] GetExistingTasks(params string[] tasklist)+ {+ List<string> foundExisting = new List<string>(tasklist.Length);++ foreach (string path in tasklist)+ {+ if (File.Exists(Path.Combine(PathLocator.Files.Tasks, path.TrimStart('\\', '/').Replace('/', '\\'))))+ foundExisting.Add(path);+ }++ return foundExisting.ToArray();+ }}}diff --git a/.Source/GTweak/View/DataSystemView.xaml b/.Source/GTweak/View/DataSystemView.xamlindex b1929b13..a997f44f 100644--- a/.Source/GTweak/View/DataSystemView.xaml+++ b/.Source/GTweak/View/DataSystemView.xaml@@ -7,7 +7,7 @@xmlns:vm="clr-namespace:GTweak.Core.ViewModel"xmlns:xrpb="http://XamlRadialProgressBar/DotNet"mc:Ignorable="d" d:DesignHeight="550" d:DesignWidth="1100"- Style="{StaticResource LaunchPage}" Unloaded="Page_Unloaded">+ Style="{StaticResource LaunchPage}" Unloaded="Page_Unloaded" Loaded="Page_Loaded"><UserControl.DataContext><vm:DataSystemVM /></UserControl.DataContext>diff --git a/.Source/GTweak/View/DataSystemView.xaml.cs b/.Source/GTweak/View/DataSystemView.xaml.csindex 1170af52..8311271f 100644--- a/.Source/GTweak/View/DataSystemView.xaml.cs+++ b/.Source/GTweak/View/DataSystemView.xaml.cs@@ -29,7 +29,6 @@ namespace GTweak.ViewInitializeComponent();_monitoringService.HandleDevicesEvents += OnHandleDevicesEvents;- _monitoringService.StartDeviceMonitoring();RAMLoad.Value = _monitoringService.GetMemoryUsage;CPULoad.Value = MonitoringService.GetProcessorUsage;@@ -67,7 +66,6 @@ namespace GTweak.ViewIpAddress.Effect.BeginAnimation(BlurEffect.RadiusProperty, FactoryAnimation.CreateTo(0.18, () => { SettingsEngine.IsHiddenIpAddress = false; }));});});- timer.Start();}private async void OnHandleDevicesEvents(MonitoringService.DeviceType deviceType) => await backgroundQueue.QueueTask(delegate { _systemDiagnostics.UpdatingDevicesData(deviceType); });@@ -134,6 +132,12 @@ namespace GTweak.View}}+ private void Page_Loaded(object sender, RoutedEventArgs e)+ {+ _monitoringService.StartDeviceMonitoring();+ timer.Start();+ }+private void Page_Unloaded(object sender, RoutedEventArgs e){_monitoringService.StopDeviceMonitoring();