我正在使用 Visual Studio 2010、C# (.Net 4)。
我有一个包含具有两列的 DataGridView 的应用程序。每列都包含我要运行的程序的参数。
现在我想从我的 C# 应用程序运行另一个具有数据网格视图中的参数的应用程序。另外,我想在运行新进程之前等待 3 秒。
我尝试了以下代码,但该过程是并行运行的,而不是一个接着一个:
private static Mutex mut = new Mutex();
public void runProgram(string executablePath, string argu1, string argu2)
{
mut.WaitOne();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = Path.GetDirectoryName(executablePath);
startInfo.FileName = "CMD.exe";
startInfo.Arguments = "/C " + set.ExecutablePath + " "
+ argu1 + " " + argu2;
try
{
Process p = Process.Start(startInfo);
//p.WaitForExit(); // don't start the next process until the first finish -> not good, stuck the app
}
catch
{
MessageBox.Show("ERROR: unsuccess to run the applicition");
}
mut.ReleaseMutex();
}
private void bu_RunProgram_Click(object sender, EventArgs e)
{
if (!File.Exists(set.ExecutablePath))
{
MessageBox.Show("The executable file doesn't exist\nPlease select right executable file in the settings form", "Error");
return;
}
int progRow;
foreach (DataGridViewRow dgvr in dg_ParametersToRun.Rows)
{
progRow = dgvr.Index;
string argu1 = dg_ParametersToRun.Rows[progRow].Cells[0].FormattedValue.ToString();
string argu2 = dg_ParametersToRun.Rows[progRow].Cells[1].FormattedValue.ToString();
Thread threadProgRun= new Thread(() => runProgram(set.ExecutablePath, argu1, argu2));
threadProgRun.Start();
Thread.Sleep(3000); // Need to come to this line only when the previous thread finish...
}
}
我以前从未使用过线程。
根据建议:
// Aid variable
int paramRowIndex;
public void runNextParameters(object sender, EventArgs e)
{
paramRowIndex++;
if (paramRowIndex > dg_RunListTests.Rows.Count) return; finish run all parameters
//run the test
string argu1 = dg_RunListTests.Rows[paramRowIndex].Cells[0].FormattedValue.ToString();
string argu2 = dg_RunListTests.Rows[paramRowIndex].Cells[1].FormattedValue.ToString();
runParameters(set.ExecutablePath, componenet, test);
}
public void runParameters(string executablePath, string argu1, string argu2)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = Path.GetDirectoryName(executablePath);
startInfo.FileName = "CMD.exe";
startInfo.Arguments = "/C " + set.ExecutablePath + " "
+ argu1 + " " + argu2;
try
{
Process p = Process.Start(startInfo);
p.Exited += runNextParameters;
}
catch
{
MessageBox.Show("Unsuccess to run the test again");
}
}
private void bu_RunParameters_Click(object sender, EventArgs e)
{
if (!File.Exists(set.ExecutablePath))
{
MessageBox.Show("The executable file doesn't exist\nPlease select right executable file in the settings form", Error);
return;
}
paramRowIndex = 0;
runNextParameters(sender, e);
}
可能的快速解决方案:启动一个 .bat 文件来启动两个(三个)程序。您必须创建另一个程序,该程序等待 3 秒才能在中间调用。