我正在实现 C# 应用程序。我需要同时在多台远程机器上执行一个程序。为此,我在具有多线程的 CMD
上使用 PSExec
。基本上,对于每台机器,我都会启动一个线程来启动 CMD
进程。根据远程执行程序的结果,如果它花费的时间超过 x 分钟,我想采取行动或终止它(希望这是有意义的)。
我遇到的问题是,除了使用 WaitForExit
之外,我真的不知道如何控制进程运行了多长时间,而且,这并不能真正让我进行多重操作-线程等待 CMD
调用完成。
我确信一定有办法做到这一点,但我真的想不通。谁能帮帮我?
这是我的代码(我是 c# 编码的新手,所以可能不是最好的代码,请随时更正您认为不正确的任何部分):
public async void BulkExecution()
{
//Some code
foreach (string machine in Machines)
{
//more code to work out the CMDline and other duties.
var result = Task.Factory.StartNew(r => ExecutePsexec((string)r, RunBeforeKillMsec), CMDLine);
await result;
}
//More Code
}
private static void ExecutePsexec(string CMDline, int RunBeforeKillMsec)
{
Process compiler = new Process();
compiler.StartInfo.FileName = "psexec.exe";
compiler.StartInfo.Arguments = CMDline;
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
if (!compiler.WaitForExit(RunBeforeKillMsec))
{
ExecutePSKill(CMDline);
}
else
{
//Some Actions here
Common.Log(LogFile, CMDline.Split(' ')[0] + " finished successfully");
}
}
最佳答案
ExecutePsexec
在单独的任务中运行。所有这些任务都是独立的。 await result;
是对它们进行排序的内容。您需要将其删除。
关于c# - 执行多个CMD任务并异步更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662867/