Skip to content

Commit 652e3bd

Browse files
committed
Improve process killer performance
1 parent f583041 commit 652e3bd

File tree

1 file changed

+32
-11
lines changed

1 file changed

+32
-11
lines changed

Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
using Microsoft.Win32.SafeHandles;
2-
using System;
1+
using System;
2+
using System.Collections.Concurrent;
33
using System.Collections.Generic;
44
using System.Diagnostics;
55
using System.Linq;
66
using System.Text;
7+
using System.Threading.Tasks;
8+
using Microsoft.Win32.SafeHandles;
79
using Windows.Win32;
810
using Windows.Win32.Foundation;
911
using Windows.Win32.System.Threading;
@@ -72,8 +74,21 @@ public List<Process> GetMatchingProcesses()
7274
/// </summary>
7375
public static unsafe Dictionary<int, string> GetProcessesWithNonEmptyWindowTitle()
7476
{
75-
var processDict = new Dictionary<int, string>();
77+
// Collect all window handles
78+
var windowHandles = new List<HWND>();
7679
PInvoke.EnumWindows((hWnd, _) =>
80+
{
81+
if (PInvoke.IsWindowVisible(hWnd))
82+
{
83+
windowHandles.Add(hWnd);
84+
}
85+
return true;
86+
}, IntPtr.Zero);
87+
88+
// Concurrently process each window handle
89+
var processDict = new ConcurrentDictionary<int, string>();
90+
var processedProcessIds = new ConcurrentDictionary<int, byte>();
91+
Parallel.ForEach(windowHandles, hWnd =>
7792
{
7893
var windowTitle = GetWindowTitle(hWnd);
7994
if (!string.IsNullOrWhiteSpace(windowTitle) && PInvoke.IsWindowVisible(hWnd))
@@ -82,20 +97,26 @@ public static unsafe Dictionary<int, string> GetProcessesWithNonEmptyWindowTitle
8297
var result = PInvoke.GetWindowThreadProcessId(hWnd, &processId);
8398
if (result == 0u || processId == 0u)
8499
{
85-
return false;
100+
return;
86101
}
87102

88-
var process = Process.GetProcessById((int)processId);
89-
if (!processDict.ContainsKey((int)processId))
103+
// Ensure each process ID is processed only once
104+
if (processedProcessIds.TryAdd((int)processId, 0))
90105
{
91-
processDict.Add((int)processId, windowTitle);
106+
try
107+
{
108+
var process = Process.GetProcessById((int)processId);
109+
processDict.TryAdd((int)processId, windowTitle);
110+
}
111+
catch
112+
{
113+
// Handle exceptions (e.g., process exited)
114+
}
92115
}
93116
}
117+
});
94118

95-
return true;
96-
}, IntPtr.Zero);
97-
98-
return processDict;
119+
return new Dictionary<int, string>(processDict);
99120
}
100121

101122
private static unsafe string GetWindowTitle(HWND hwnd)

0 commit comments

Comments
 (0)