Sage.WindowsProcess 1.0.0.7

dotnet add package Sage.WindowsProcess --version 1.0.0.7
                    
NuGet\Install-Package Sage.WindowsProcess -Version 1.0.0.7
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sage.WindowsProcess" Version="1.0.0.7" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sage.WindowsProcess" Version="1.0.0.7" />
                    
Directory.Packages.props
<PackageReference Include="Sage.WindowsProcess" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Sage.WindowsProcess --version 1.0.0.7
                    
#r "nuget: Sage.WindowsProcess, 1.0.0.7"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Sage.WindowsProcess@1.0.0.7
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Sage.WindowsProcess&version=1.0.0.7
                    
Install as a Cake Addin
#tool nuget:?package=Sage.WindowsProcess&version=1.0.0.7
                    
Install as a Cake Tool

Sage.WindowsProcess

简介

Sage.WindowsProcess 是一个功能强大的 Windows 进程管理库, 提供了全面的进程生命周期管理、监控和控制功能。该库专为 .NET 应用程序设计,完全兼容 AOT 编译 。它支持异步操作、事件通知和动态配置,适用于需要高可靠性和灵活性的进程管理应用场景。

主要特性

进程管理

  • 完整生命周期控制:配置需要启动、停止、重启和监控进程
  • 超时控制:所有异步操作支持超时参数
  • 标准输入/输出:重定向和处理进程的标准输入、输出和错误流(可用于获取控制台程序输出打印的信息,支持获取程序Console输出的内容)
  • 进程状态监控:实时获取进程状态信息(运行状态、CPU和内存使用率等)
  • 自动重启:可配置的进程崩溃自动恢复机制
  • 批量操作:支持同时管理多个进程
  • 进程优先级:动态调整已配置进程的系统优先级

其它特性

  • 事件通知:丰富的事件系统,用于监听进程状态变化
  • 动态配置:运行时添加或移除进程配置
  • 异步API:全面的异步支持,包括取消令牌
  • AOT兼容:完全支持提前编译(Ahead-of-Time),适用于高性能场景

其它功能

  • 开机自启动:支持将自身或指定应用程序配置为Windows开机启动
  • 父进程信息:获取调用进程的父进程信息(如命令行shell、cmd等)

安装

dotnet add package Sage.WindowsProcess

使用示例

基本配置与初始化

using Sage.WindowsProcess.Services;
using Sage.WindowsProcess.Configuration;
using Sage.WindowsProcess.Events;
using Sage.WindowsProcess.Models;

// 创建进程配置
var config = new ProcessConfig
{
    Key = "notepad",                  // 进程唯一标识符
    ExecutablePath = "notepad.exe",  // 可执行文件路径
    Arguments = "example.txt",       // 命令行参数
    WorkingDirectory = Environment.CurrentDirectory,  // 工作目录
    AutoRestart = true,              // 进程崩溃时自动重启
    MaxRestartAttempts = 3,          // 最大重启尝试次数
    RedirectOutput = true,           // 重定向标准输出和错误流
    CreateNoWindow = true,           // 不创建新窗口
    EnableMonitoring = true,         // 启用资源监控
    MonitoringIntervalMs = 5000,     // 监控间隔(毫秒)
    ProcessPriority = System.Diagnostics.ProcessPriorityClass.Normal  // 进程优先级
};

// 创建进程管理服务
var processManager = new ProcessManagerService(new[] { config });

事件处理

// 进程启动事件
processManager.ProcessStarted += (sender, e) =>
{
    Console.WriteLine($"进程已启动:{e.ProcessKey}, PID: {e.ProcessId}");
};

// 进程停止事件
processManager.ProcessExited += (sender, e) =>
{
    Console.WriteLine($"进程已停止:{e.ProcessKey}, 退出代码: {e.ExitCode}");
};

// 进程标准输出事件
processManager.ProcessOutput += (sender, e) =>
{
    Console.WriteLine($"[{e.ProcessKey}] 输出: {e.Data}");
};

// 进程错误输出事件
processManager.ProcessError += (sender, e) =>
{
    Console.WriteLine($"[{e.ProcessKey}] 错误: {e.Data}");
};

// 进程状态更新事件
processManager.ProcessStatusUpdated += (sender, e) =>
{
    Console.WriteLine($"[{e.ProcessKey}] CPU: {e.Status.CpuUsage}%, 内存: {e.Status.MemoryUsageMB}MB");
};

// 服务错误事件
processManager.ProcessServiceError += (sender, e) =>
{
    Console.WriteLine($"服务错误: {e.Message}, 进程: {e.ProcessKey}");
};

进程生命周期管理

// 启动进程(带超时参数)
await processManager.StartAsync("notepad", timeout: 60000);  // 等待60秒超时

// 启动所有已配置的进程
await processManager.StartAllAsync(timeout: 30000);  // 等待30秒超时

// 向进程标准输入写入数据
await processManager.WriteToStandardInputAsync("notepad", "Hello World");

// 等待进程退出(带超时参数)
await processManager.WaitForExitAsync("notepad", timeout: 5000);  // 等待5秒超时

// 停止进程(带超时参数)
await processManager.StopAsync("notepad", timeout: 3000);  // 等待3秒超时

// 停止所有进程
await processManager.StopAllAsync(timeout: 5000);  // 等待5秒超时

// 重启进程(带启动和停止超时参数)
await processManager.RestartAsync("notepad", startTimeout: 30000, stopTimeout: 5000);

进程状态与控制

// 检查进程是否正在运行
bool isRunning = processManager.IsRunning("notepad");

// 获取进程状态信息
var status = processManager.GetStatus("notepad");
if (status != null)
{
    Console.WriteLine($"进程状态:{status.State}");
    Console.WriteLine($"CPU使用率:{status.CpuUsage}%");
    Console.WriteLine($"内存使用:{status.MemoryUsageMB}MB");
    Console.WriteLine($"运行时间:{status.RunningTimeSpan}");
}

// 动态修改进程优先级
processManager.SetProcessPriority("notepad", System.Diagnostics.ProcessPriorityClass.High);

动态管理进程配置

// 动态添加新进程
var newConfig = new ProcessConfig
{
    Key = "calculator",
    ExecutablePath = "calc.exe",
    AutoRestart = false,
    ProcessPriority = System.Diagnostics.ProcessPriorityClass.Normal
};

// 添加单个进程配置
processManager.AddConfig(newConfig);

// 添加多个进程配置
var configs = new List<ProcessConfig>
{
    new ProcessConfig
    {
        Key = "cmd",
        ExecutablePath = "cmd.exe",
        Arguments = "/c dir",
        RedirectOutput = true
    },
    new ProcessConfig
    {
        Key = "powershell",
        ExecutablePath = "powershell.exe",
        Arguments = "-Command \"Get-Process\"",
        RedirectOutput = true
    }
};
processManager.AddConfig(configs);//重载支持List

// 启动新添加的进程
await processManager.StartAsync("calculator", timeout: 30000);

// 动态移除进程(可选择是否先停止进程)
await processManager.RemoveConfigAsync("calculator", stopRunning: true);

获取父进程信息

using Sage.WindowsProcess.Parent;

// 获取父进程完整信息
var parentInfo = ParentProcessUtility.GetParentProcessInfo();

// 检查信息是否有效
if (parentInfo.IsValid())
{
    Console.WriteLine($"父进程ID: {parentInfo.Id}");
    Console.WriteLine($"父进程名称: {parentInfo.Name}");
    Console.WriteLine($"父进程路径: {parentInfo.Path}");
    Console.WriteLine($"命令行: {parentInfo.CommandLine}");
}
else
{
    Console.WriteLine("无法获取有效的父进程信息");
}

资源释放

// 同步释放资源
processManager.Dispose();

// 异步释放资源
await processManager.DisposeAsync();

高级用法

自定义进程监控

// 创建带有自定义监控设置的进程配置
var monitoredConfig = new ProcessConfig
{
    Key = "monitored-app",
    ExecutablePath = "path/to/your/app.exe",
    EnableMonitoring = true,           // 启用监控
    MonitoringIntervalMs = 2000,       // 每2秒监控一次
    AutoRestart = true,                // 进程崩溃时自动重启
    RestartDelayMs = 1000,             // 重启前等待1秒
    MaxRestartAttempts = 5             // 最多尝试重启5次
};

// 注册状态更新事件以实现自定义监控逻辑
processManager.ProcessStatusUpdated += (sender, e) =>
{
    // 示例:当CPU使用率超过80%时记录警告
    if (e.Status.CpuUsage > 80)
    {
        Console.WriteLine($"警告: 进程 {e.ProcessKey} CPU使用率过高: {e.Status.CpuUsage}%");
    }
    
    // 示例:当内存使用超过500MB时记录警告
    if (e.Status.MemoryUsageMB > 500)
    {
        Console.WriteLine($"警告: 进程 {e.ProcessKey} 内存使用过高: {e.Status.MemoryUsageMB}MB");
    }
};

取消令牌支持

// 创建取消令牌源
using var cts = new CancellationTokenSource();

// 启动进程并支持取消
var startTask = processManager.StartAsync("long-running-process", timeout: 30000);

// 在另一个任务中,如果需要取消操作
cts.CancelAfter(TimeSpan.FromSeconds(10)); // 10秒后取消

try
{
    // 等待进程写入标准输入,支持取消
    await processManager.WriteToStandardInputAsync("long-running-process", "some input", cts.Token);
    
    // 等待进程退出,支持取消
    await processManager.WaitForExitAsync("long-running-process", timeout: 10000, cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("操作已取消");
}

开机启动设置


// 提供了IStartupService接口和StartupService实现类,用于设置应用程序开机启动。
// 使用方法1 设置自身开机启动,仅需要添加名称即可
StartupService startupService1 = new("应用名称");

// 使用方法2 设置其他应用开机启动,需要添加扩展名,还有完整的程序路径。
StartupService startupService2 = new("应用程序名称","其他需要开机启动的程序路径(完整路径包含程序扩展)");

// 使用方法3 无论是设置自身还是其他程序,都支持设置命令行参数
StartupService startupService3 = new("应用程序名称", "其他需要开机启动的程序路径(完整路径包含程序扩展)","- f -t");

// 设置开启启动
startupService1.SetStartup();
// 移除开机启动
startupService1.RemoveStartup();

// 检查是否已设置开机启动
bool isStartup = startupService1.IsStartupSet();

许可证

版权所有 © 2025 甲壳虫科技 团队。

贡献

欢迎提交问题和功能请求。 QQ Group: 1054304346

作者

甲壳虫科技

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0.7 122 9/23/2025
1.0.0.6 146 8/20/2025
1.0.0.5 154 8/20/2025
1.0.0.4 154 8/20/2025
1.0.0.3 136 8/19/2025
1.0.0.2 149 8/19/2025
1.0.0.1 148 8/19/2025
1.0.0 136 7/16/2025

更新基础库