在工作线程中运行进程(c#)
本文关键字:进程 运行 工作 线程 | 更新日期: 2023-09-27 18:09:31
我试图从我的应用程序内部运行几个外部应用程序。假设我想运行一个名为LongtimeRun.exe的应用程序10次,每次该应用程序运行时,大约需要30秒才能完成(总时间为300秒或5分钟!)。我还想给用户一些进度指示(例如,应用程序运行了多少次)。
我可以创建一个批处理文件并在那里运行LongTimeRun.exe 10次,但随后我无法显示任何进度报告。
我有这样的代码:
using System.Diagnostics;
using System.IO;
public class CommandProcessor
{
private readonly string binDirectory;
private readonly string workingDirectory;
public CommandProcessor(string workingDirectory, string binFolderName)
{
binDirectory = Path.Combine(FileSystem.ApplicationDirectory, binFolderName);
this.workingDirectory = workingDirectory;
}
public int RunCommand(string command, string argbase, params string[] args)
{
var commandPath = Path.Combine(binDirectory, command);
var formattedArgumets = string.Format(argbase, args);
var myProcess = new Process();
myProcess.EnableRaisingEvents = false;
myProcess.StartInfo.FileName = commandPath;
myProcess.StartInfo.Arguments = formattedArgumets;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.WorkingDirectory = this.workingDirectory;
myProcess.Start();
myProcess.WaitForExit();
}
}
当我这样调用它时:
private void RunCommands()
{
var command = "LongRunCommand.exe";
string binDirectory = Path.Combine(FileSystem.ApplicationDirectory, binFolderName);
var cp = new CommandProcessor(this.workingDirectory, binDirectory);
for(int i=0;i<10;i++)
{
cp.RunCommand(Command, "-i {0}", i);
}
}
上面的代码作为直接调用的一部分被调用,并阻塞应用程序(在此过程中应用程序似乎挂起)。
为了解决挂起问题,我使用了一个后台worker,如下所示:
var worker = new BackgroundWorker();
worker.DoWork += this.WorkerDoWork;
worker.RunWorkerCompleted += this.workerRunWorkerCompleted;
worker.RunWorkerAsync();
在WorkerDoWork中调用runcommand
现在应用程序在调用这一行后退出:
myProcess.WaitForExit();
没有调试信息,退出码为-1
问题是什么?如何解决?
有没有更好的方法来实现我的目标,而不使用BackgroundWorker?
你遇到的问题是因为你的BackgroundWorker
线程仍然在运行,但是你的应用程序完成了它的生命周期并结束了(它没有被它们阻塞,所以它的路径是清晰的),因此杀死了这些线程。
你需要通知应用程序NOT在后台线程还在运行的时候退出。你可以设置一个计数器,在每个线程启动时递增,然后在线程完成时递减。
在你的主应用程序线程中,你可以等到计数器为零才结束应用程序。
显然,你需要考虑锁定(即两个线程试图同时减少计数器),但这应该给你一个开始