1

在 C# 中执行内置 shell 命令除了 Process 之外还有其他选择吗?目前我正在使用 Process 类来运行这些命令。但在当前场景中,我想并行运行 200 多个这样的命令。所以产生超过 200 个进程并不是一个好主意。还有其他选择吗?

4

3 回答 3

2

“运行一个dos命令”相当于“创建一个进程并运行它”,所以即使有另一个api,仍然会有200个进程(顺便说一句,除非你在一个非常非常小的系统)

于 2012-05-16T10:09:55.567 回答
0

你可以但不应该这样做

using Microsoft.VisualBasic;

Interaction.Shell(...);

注意:您必须添加对 VisualBasic 程序集的引用。

这是对您问题的直接回答,但不是您应该做的事情。

于 2012-05-16T10:26:54.043 回答
0

正如 Max Keller 所指出的,System.Diagnostics.Process总是启动一个新的系统进程。

如果必须启动进程/操作超过几秒钟,我宁愿将所有命令保存在一个临时文件中并使用System.Diagnostics.Process而不是单个操作来执行它。

// Get a temp file
string tempFilepath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MyBatchFile.bat");
// Ensure the file dont exists yet
if (System.IO.File.Exists(tempFilepath)) {
    System.IO.File.Delete(tempFilepath);
}
// Create some operations
string[] batchOperations = new string[]{
    "START netstat -a",
    "START systeminfo"
};
// Write the temp file
System.IO.File.WriteAllLines(tempFilepath, batchOperations);

// Create process
Process myProcess = new Process();
try {
    // Full filepath to the temp file
    myProcess.StartInfo.FileName = tempFilepath;
    // Execute it
    myProcess.Start();
    // This code assumes the process you are starting will terminate itself!
} catch (Exception ex) {
    // Output any error to the console
    Console.WriteLine(ex.Message);
}

// Remove the temp file
System.IO.File.Delete(tempFilepath);
于 2012-05-16T10:33:19.637 回答