我在使用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);
}
答案 0 :(得分:0)
可能的快速解决方案:启动一个启动两(3)个程序的.bat文件。你必须创建另一个等待3秒钟的程序。