关于多线程:异步在C#中对shell的调用是否打开一个新线程?

Async Call to shell in C# is open a new thread?

本问题已经有最佳答案,请猛点这里访问。

我在以下答案中有以下代码:Process.start:如何获取输出?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static void runCommand() {
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName ="cmd.exe";
    process.StartInfo.Arguments ="/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}
static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) {
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

在我的情况下,我需要同时调用多个实例,当时我在考虑创建线程,但我知道不需要使用此代码的线程。有人可以解释一下两者之间的区别吗?如果有必要,可以让一个线程进行异步调用吗?
提前致谢。亲切的问候


如果您需要运行多个调用,则由于WaitForExit()会阻塞,因此必须使用其他策略。

如果您不需要知道何时完成,只需删除WaitForExit()即可,因为您不需要同步上下文。

如果您需要知道流程何时完成,则可以选择线程化,但是,为许多人生成线程和流程效率很低-您可以利用带有某些内务处理的Process Exit Event来跟踪完成情况,然后发出自己的事件来发出结论。


如果要并行运行进程,则必须稍稍更改代码。该行" process.WaitForExit();"不是您想要的(根据您的描述)

请参阅MSDN:

WaitForExit() makes the current thread wait until the associated process terminates. It should be called after all other methods are called on the process. To avoid blocking the current thread, use the Exited event.

因此,如果您想在循环中执行此操作的多个实例,请不要在等待时阻塞主线程(这会创建其他cmd进程)。