'GetProcessDiagnosticInfos() returns empty without Thread.Sleep in AppDiagnosticInfoWatcher

I searched about AppDiagnosticInfoWatcher, but I don't find almost any resources. What I try in this example is to create an instance of AppDiagnosticInfoWatcher (monitors when a new UWP app launches) and use the Added event to close the UWP app. The problem is, sometimes the foreach on resourceGroup.GetProcessDiagnosticInfos() returns empty and Thread.Sleep make it to work, I'm not sure if that's a permanent solution though. Thanks for any help!

uwpWatcher = AppDiagnosticInfo.CreateWatcher();
uwpWatcher.Added += OnNewUwpProcess;

private void OnNewUwpProcess(AppDiagnosticInfoWatcher sender, AppDiagnosticInfoWatcherEventArgs args) 
{
    foreach (var resourceGroup in args.AppDiagnosticInfo.GetResourceGroups())
    {
         // Without this Thread.Sleep the following foreach sometimes returns empty
         Thread.Sleep(1000);
         foreach (var processDiagnosticInfo in resourceGroup.GetProcessDiagnosticInfos())
         {
             var process = Process.GetProcessById((int)processDiagnosticInfo.ProcessId);
             process.Kill();
         }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source