Repository navigation
Expand file tree
/
Copy pathProcessManager.cs
More file actions
705 lines (634 loc) · 23.4 KB
/
Copy pathProcessManager.cs
File metadata and controls
705 lines (634 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace ProcessFreezer
{
/// <summary>
/// 进程管理器 - 核心内存清理逻辑
/// </summary>
public class ProcessManager
{
private static readonly object IconCacheLock = new();
private static readonly Dictionary<string, ImageSource?> IconCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly object PriorityLock = new();
private static readonly Dictionary<int, ProcessPriorityClass> OriginalPriorityByPid = new();
public static ImageSource? GetCachedProcessIcon(string processName)
{
var cacheKey = processName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
? processName
: processName + ".exe";
lock (IconCacheLock)
{
return IconCache.TryGetValue(cacheKey, out var cached) ? cached : null;
}
}
/// <summary>
/// 清理结果
/// </summary>
public class TrimResult
{
public string ProcessName { get; set; } = "";
public int ProcessId { get; set; }
public long MemoryBeforeMB { get; set; }
public long MemoryAfterMB { get; set; }
public long FreedMB => MemoryBeforeMB - MemoryAfterMB;
public bool Success { get; set; }
public string? ErrorMessage { get; set; }
}
/// <summary>
/// 监控进程(用于主列表显示,支持实时更新)
/// </summary>
public class MonitoredProcess : INotifyPropertyChanged
{
public string Name { get; set; } = "";
public ImageSource? Icon { get; set; }
private long _workingSetMB;
public long WorkingSetMB
{
get => _workingSetMB;
set { _workingSetMB = value; OnPropertyChanged(nameof(WorkingSetMB)); OnPropertyChanged(nameof(MemoryDisplay)); }
}
private long _virtualMemoryMB;
public long VirtualMemoryMB
{
get => _virtualMemoryMB;
set { _virtualMemoryMB = value; OnPropertyChanged(nameof(VirtualMemoryMB)); OnPropertyChanged(nameof(MemoryDisplay)); }
}
public string MemoryDisplay => $"物理内存(WS): {WorkingSetMB} MB | 虚拟内存(Commit): {VirtualMemoryMB} MB";
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
/// <summary>
/// 进程信息(用于进程选择器显示)
/// </summary>
public class ProcessInfo
{
public string Name { get; set; } = "";
public int Pid { get; set; }
public int InstanceCount { get; set; }
public long WorkingSetMB { get; set; }
public long PrivateMemoryMB { get; set; }
public long VirtualMemoryMB { get; set; }
public ImageSource? Icon { get; set; }
public string DisplayName => InstanceCount > 1 ? $"{Name} ({InstanceCount})" : Name;
public string MemoryDisplay => $"物理内存(WS): {WorkingSetMB} MB | 虚拟内存(Commit): {VirtualMemoryMB} MB";
public override string ToString() => $"{Name} - {WorkingSetMB} MB";
}
public class ProcessRuntimeInfo
{
public string Name { get; set; } = "";
public int Pid { get; set; }
public long WorkingSetMB { get; set; }
}
/// <summary>
/// 从进程获取图标
/// </summary>
public static ImageSource? GetProcessIcon(string processName)
{
var cacheKey = processName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
? processName
: processName + ".exe";
lock (IconCacheLock)
{
if (IconCache.TryGetValue(cacheKey, out var cached))
{
return cached;
}
}
try
{
var name = processName.Replace(".exe", "", StringComparison.OrdinalIgnoreCase);
var processes = Process.GetProcessesByName(name);
if (processes.Length == 0)
{
lock (IconCacheLock)
{
IconCache[cacheKey] = null;
}
return null;
}
var process = processes[0];
string? path = null;
try { path = process.MainModule?.FileName; } catch { }
foreach (var p in processes) p.Dispose();
if (string.IsNullOrEmpty(path))
{
lock (IconCacheLock)
{
IconCache[cacheKey] = null;
}
return null;
}
using var icon = System.Drawing.Icon.ExtractAssociatedIcon(path);
if (icon == null) return null;
var source = Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
source.Freeze();
lock (IconCacheLock)
{
IconCache[cacheKey] = source;
}
return source;
}
catch
{
lock (IconCacheLock)
{
if (!IconCache.ContainsKey(cacheKey))
{
IconCache[cacheKey] = null;
}
}
return null;
}
}
/// <summary>
/// 获取指定进程的当前内存使用量
/// </summary>
public static (long workingSetMB, long virtualMemoryMB) GetProcessMemory(string processName)
{
try
{
var name = processName.Replace(".exe", "", StringComparison.OrdinalIgnoreCase);
var processes = Process.GetProcessesByName(name);
long workingSet = 0, commitMemory = 0;
foreach (var p in processes)
{
try
{
workingSet += p.WorkingSet64 / (1024 * 1024);
commitMemory += GetCommitMemoryMB(p);
}
catch { }
p.Dispose();
}
return (workingSet, commitMemory);
}
catch
{
return (0, 0);
}
}
/// <summary>
/// 获取所有运行中的进程名列表
/// </summary>
public static List<string> GetRunningProcessNames()
{
try
{
return Process.GetProcesses()
.Select(p => p.ProcessName + ".exe")
.Distinct()
.OrderBy(n => n)
.ToList();
}
catch
{
return new List<string>();
}
}
/// <summary>
/// 获取所有运行中的进程详细信息(按内存占用排序)
/// </summary>
public static List<ProcessInfo> GetRunningProcessesInfo(bool includeIcons = true, bool fastMemory = false)
{
var result = new List<ProcessInfo>();
try
{
if (!includeIcons && fastMemory)
{
var map = new Dictionary<string, ProcessInfo>(StringComparer.OrdinalIgnoreCase);
foreach (var process in Process.GetProcesses())
{
try
{
var key = process.ProcessName;
if (!map.TryGetValue(key, out var info))
{
info = new ProcessInfo
{
Name = key + ".exe",
Pid = process.Id,
InstanceCount = 0,
WorkingSetMB = 0,
PrivateMemoryMB = 0,
VirtualMemoryMB = 0,
Icon = GetCachedProcessIcon(key)
};
map[key] = info;
}
info.InstanceCount++;
info.WorkingSetMB += process.WorkingSet64 / (1024 * 1024);
info.PrivateMemoryMB += process.PrivateMemorySize64 / (1024 * 1024);
info.VirtualMemoryMB = info.PrivateMemoryMB;
}
catch
{
// ignore per-process failures
}
finally
{
process.Dispose();
}
}
return map.Values
.OrderByDescending(p => p.WorkingSetMB)
.ToList();
}
var processes = Process.GetProcesses();
var grouped = processes
.GroupBy(p => p.ProcessName, StringComparer.OrdinalIgnoreCase)
.Select(g =>
{
long workingSet = 0, commitMemory = 0;
foreach (var p in g)
{
try
{
workingSet += p.WorkingSet64 / (1024 * 1024);
commitMemory += fastMemory
? p.PrivateMemorySize64 / (1024 * 1024)
: GetCommitMemoryMB(p);
}
catch { }
}
return new ProcessInfo
{
Name = g.Key + ".exe",
Pid = g.First().Id,
InstanceCount = g.Count(),
WorkingSetMB = workingSet,
PrivateMemoryMB = commitMemory,
VirtualMemoryMB = commitMemory,
Icon = includeIcons ? GetProcessIcon(g.Key) : null
};
})
.OrderByDescending(p => p.WorkingSetMB)
.ToList();
foreach (var p in processes) p.Dispose();
return grouped;
}
catch
{
return result;
}
}
/// <summary>
/// 获取进程的工作集大小(MB)
/// </summary>
public static long GetWorkingSetMB(Process process)
{
try
{
return process.WorkingSet64 / (1024 * 1024);
}
catch
{
return 0;
}
}
public static List<ProcessRuntimeInfo> GetRunningTargetProcesses(IEnumerable<string> processNames)
{
var result = new List<ProcessRuntimeInfo>();
try
{
var targetNames = processNames
.Select(n => n.Replace(".exe", "", StringComparison.OrdinalIgnoreCase))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var process in Process.GetProcesses())
{
try
{
if (!targetNames.Contains(process.ProcessName))
{
continue;
}
result.Add(new ProcessRuntimeInfo
{
Name = process.ProcessName,
Pid = process.Id,
WorkingSetMB = GetWorkingSetMB(process)
});
}
catch
{
// ignore per-process failures
}
finally
{
process.Dispose();
}
}
}
catch
{
// ignore and return what we have
}
return result;
}
public static TrimResult TrimProcessById(int pid, long thresholdMB)
{
try
{
using var process = Process.GetProcessById(pid);
var memoryBeforeMB = GetWorkingSetMB(process);
if (memoryBeforeMB < thresholdMB)
{
return new TrimResult
{
ProcessName = process.ProcessName,
ProcessId = pid,
MemoryBeforeMB = memoryBeforeMB,
MemoryAfterMB = memoryBeforeMB,
Success = false,
ErrorMessage = "低于阈值"
};
}
return TrimSingleProcess(process, memoryBeforeMB);
}
catch (Exception ex)
{
return new TrimResult
{
ProcessName = $"PID:{pid}",
ProcessId = pid,
Success = false,
ErrorMessage = ex.Message
};
}
}
public static bool TryGetPriority(int pid, out ProcessPriorityClass priority)
{
priority = ProcessPriorityClass.Normal;
try
{
using var process = Process.GetProcessById(pid);
priority = process.PriorityClass;
return true;
}
catch
{
return false;
}
}
public static bool TrySetPriority(int pid, ProcessPriorityClass priority)
{
try
{
using var process = Process.GetProcessById(pid);
process.PriorityClass = priority;
return true;
}
catch
{
return false;
}
}
public static void SyncMonitoredPriorities(HashSet<string> monitoredNames, bool shouldLower)
{
var currentTargetPids = new HashSet<int>();
foreach (var process in Process.GetProcesses())
{
try
{
if (!monitoredNames.Contains(process.ProcessName))
{
continue;
}
currentTargetPids.Add(process.Id);
if (!shouldLower)
{
continue;
}
lock (PriorityLock)
{
if (!OriginalPriorityByPid.ContainsKey(process.Id))
{
OriginalPriorityByPid[process.Id] = process.PriorityClass;
}
}
process.PriorityClass = ProcessPriorityClass.BelowNormal;
}
catch
{
// ignore per-process failures
}
finally
{
process.Dispose();
}
}
List<int> restorePids;
lock (PriorityLock)
{
restorePids = OriginalPriorityByPid.Keys
.Where(pid => !shouldLower || !currentTargetPids.Contains(pid))
.ToList();
}
foreach (var pid in restorePids)
{
ProcessPriorityClass original;
lock (PriorityLock)
{
if (!OriginalPriorityByPid.TryGetValue(pid, out original))
{
continue;
}
}
if (TrySetPriority(pid, original) || !currentTargetPids.Contains(pid))
{
lock (PriorityLock)
{
OriginalPriorityByPid.Remove(pid);
}
}
}
}
public static void RestoreAllTrackedPriorities()
{
List<KeyValuePair<int, ProcessPriorityClass>> snapshots;
lock (PriorityLock)
{
snapshots = OriginalPriorityByPid.ToList();
}
foreach (var pair in snapshots)
{
if (TrySetPriority(pair.Key, pair.Value) || !ProcessExists(pair.Key))
{
lock (PriorityLock)
{
OriginalPriorityByPid.Remove(pair.Key);
}
}
}
}
private static bool ProcessExists(int pid)
{
try
{
using var process = Process.GetProcessById(pid);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 获取进程提交内存(Commit, MB)
/// </summary>
public static long GetCommitMemoryMB(Process process)
{
IntPtr hProcess = IntPtr.Zero;
try
{
hProcess = NativeMethods.OpenProcess(
NativeMethods.PROCESS_QUERY_INFORMATION | NativeMethods.PROCESS_VM_READ,
false,
process.Id);
if (hProcess == IntPtr.Zero)
{
return process.PrivateMemorySize64 / (1024 * 1024);
}
var counters = new NativeMethods.PROCESS_MEMORY_COUNTERS
{
cb = (uint)Marshal.SizeOf<NativeMethods.PROCESS_MEMORY_COUNTERS>()
};
if (NativeMethods.GetProcessMemoryInfo(hProcess, out counters, counters.cb))
{
return (long)counters.PagefileUsage / (1024 * 1024);
}
return process.PrivateMemorySize64 / (1024 * 1024);
}
catch
{
try
{
return process.PrivateMemorySize64 / (1024 * 1024);
}
catch
{
return 0;
}
}
finally
{
if (hProcess != IntPtr.Zero)
{
NativeMethods.CloseHandle(hProcess);
}
}
}
/// <summary>
/// 清理指定进程名的所有实例
/// </summary>
public static List<TrimResult> TrimProcesses(IEnumerable<string> processNames, long thresholdMB)
{
var results = new List<TrimResult>();
var targetNames = processNames
.Select(n => n.Replace(".exe", "", StringComparison.OrdinalIgnoreCase))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var process in Process.GetProcesses())
{
try
{
if (!targetNames.Contains(process.ProcessName))
continue;
var memoryBeforeMB = GetWorkingSetMB(process);
// 如果内存占用低于阈值,跳过
if (memoryBeforeMB < thresholdMB)
continue;
var result = TrimSingleProcess(process, memoryBeforeMB);
results.Add(result);
}
catch (Exception ex)
{
results.Add(new TrimResult
{
ProcessName = process.ProcessName,
ProcessId = 0,
Success = false,
ErrorMessage = ex.Message
});
}
finally
{
process.Dispose();
}
}
return results;
}
/// <summary>
/// 清理单个进程
/// </summary>
private static TrimResult TrimSingleProcess(Process process, long memoryBeforeMB)
{
var result = new TrimResult
{
ProcessName = process.ProcessName,
ProcessId = process.Id,
MemoryBeforeMB = memoryBeforeMB
};
IntPtr hProcess = IntPtr.Zero;
try
{
// 打开进程句柄
hProcess = NativeMethods.OpenProcess(
NativeMethods.PROCESS_QUERY_INFORMATION | NativeMethods.PROCESS_SET_QUOTA,
false,
process.Id);
if (hProcess == IntPtr.Zero)
{
result.Success = false;
result.ErrorMessage = "无法打开进程句柄";
return result;
}
// 清空工作集
bool success = NativeMethods.EmptyWorkingSet(hProcess);
if (!success)
{
result.Success = false;
result.ErrorMessage = "EmptyWorkingSet 调用失败";
return result;
}
// 刷新进程信息并获取清理后的内存
process.Refresh();
result.MemoryAfterMB = GetWorkingSetMB(process);
result.Success = true;
}
catch (System.ComponentModel.Win32Exception ex)
{
result.Success = false;
result.ErrorMessage = ex.NativeErrorCode == 5 ? "访问被拒绝" : ex.Message;
}
catch (InvalidOperationException)
{
result.Success = false;
result.ErrorMessage = "进程已退出";
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = ex.Message;
}
finally
{
if (hProcess != IntPtr.Zero)
{
NativeMethods.CloseHandle(hProcess);
}
}
return result;
}
}
}