I am creating an app for monitoring earbuds that are paired with my PC. The app is made using WPF and .Net 8.0. When the app is kept open without interaction (idle), it has a low CPU usage. However, when I create some object and then remove them after disposing, CPU count remains high.
I used the Task Manager
and the Windows Assessment and Deployment Kit (Windows ADK)
to monitor CPU usage. My PC has 7 paired devices and the CPU count for idle state in the second case is approximately 60,000. On the other hand, CPU count is significantly lower (around 200) for the first case.
Looks like the objects are still being monitored even after their disposal. Is there any way to keep the CPU count low in idle state?
My .cs file:
public partial class MainWindow : Window
{
public List<BluetoothDevice> pairedDevice = new List<BluetoothDevice>();
public List<string> IdList;
public MainWindow()
{
InitializeComponent();
IdList = new List<string>()
{
//IDs of my paired buds
};
}
private async void Start_Button_Click(object sender, RoutedEventArgs e)
{
StatusBorder.Background = new SolidColorBrush(Colors.Green);
for (int i = 0; i < IdList.Count; i++)
{
BluetoothDevice temp = await BluetoothDevice.FromIdAsync(IdList[i]);
temp.ConnectionStatusChanged += OnBudsConnectionStatusChanged;
pairedDevice.Add(temp);
Debug.WriteLine($"id: {IdList[i]}, {pairedDevice != null}");
}
}
private void OnBudsConnectionStatusChanged(BluetoothDevice sender, object args)
{
Debug.WriteLine($"Connection status changed to : {sender.ConnectionStatus}");
}
private async void Stop_Button_Click(object sender, RoutedEventArgs e)
{
StatusBorder.Background = new SolidColorBrush(Colors.Red);
for (int i = 0; i < IdList.Count; i++)
{
pairedDevice[i].ConnectionStatusChanged -= OnBudsConnectionStatusChanged;
pairedDevice[i].Dispose();
pairedDevice[i] = null;
}
pairedDevice.Clear();
}
}
And my Xaml file is:
<Window x:Class="BudsWatcherSample.MainWindow"
xmlns=";
xmlns:x=";
xmlns:d=";
xmlns:mc=";
xmlns:local="clr-namespace:BudsWatcherSample"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel VerticalAlignment="Center">
<Border x:Name="StatusBorder" Margin="10" Width="20" Height="5" Background="Black"/>
<Button Content="Start" Click="Start_Button_Click" Width="50"/>
<Button Content="Stop" Click="Stop_Button_Click" Width="50"/>
</StackPanel>
</Window>