c#中的System.Diagnostics.Process和c++中的CreateProcess()哪个是最好的选择

System.Diagnostics.Process in c# and CreateProcess() in c++ which one is the best choice?

本文关键字:中的 选择 Diagnostics System Process CreateProcess c++      更新时间:2023-10-16

当我想在我的应用程序(c#)中启动子进程时,c#中的System.Diagnostics.Process和c++中的CreateProcess()哪一个是更好的选择?

给subProcess参数隐藏子进程的窗口查看子流程的输出,如日志等

另外,我想为subProcess设置CPU数量和内存限制。

我想安全地杀死所有的子进程(不泄漏内存和一些)当用户停止父进程

System.Diagnostics.Process比较好。始终从托管代码调用托管代码方法。

我猜System.Diagnostics.Process将是一个很好的选择,因为您的应用程序是管理的。如果不想隐藏子进程,请不要设置:

the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_StartInfo.UseShellExecute = false;

要限制内核的数量,您必须尝试使用ProcessThread.ProcessorAffinity

using System;
using System.Diagnostics;
namespace ProcessThreadIdealProcessor
{
    class Program
    {
        static void Main(string[] args)
        {
            // Make sure there is an instance of notepad running.
            Process[] notepads = Process.GetProcessesByName("notepad");
            if (notepads.Length == 0)
                Process.Start("notepad");
            ProcessThreadCollection threads;
            //Process[] notepads; 
            // Retrieve the Notepad processes.
            notepads = Process.GetProcessesByName("Notepad");
            // Get the ProcessThread collection for the first instance
            threads = notepads[0].Threads;
            // Set the properties on the first ProcessThread in the collection
            threads[0].IdealProcessor = 0;
            threads[0].ProcessorAffinity = (IntPtr)1;
        }
    }
}

要限制内存使用集Process.MaxWorkingSet,它可以帮助您达到相关进程允许的最大工作集大小。