开发者

Batch process in c#

I am having a Java batch process which I used in C# to run process. I want to have a testcase to check whether the batch process is running or not.

I used the batch process as:

void batch_process(string process)
{
    try
    {
        string strFilePath = Path.Combine(batch_process_path, process);
        ProcessStartInfo psi = new ProcessStartInfo(strFilePath);
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        psi.WorkingDirectory = batch_process_path;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.UseShellExecute = false;
        psi.ErrorDialog = true;
    }
}

How can this test be done?

I want to write an unit test case to check whether the process will start开发者_运维技巧 or not.


when you Start your new process you need to capture the returned Process, that provides access to newly started process, useful for starting, stopping, controlling, and monitoring applications.

 Process exe = Process.Start(psi);
    ....

 if exe.HasExited() ....


You could start the process using

Process process = new Process();
string strFilePath = Path.Combine(batch_process_path, process);
process.StartInfo.FileName = strFilePath;

//this line will hold this thread until the process is done.
process.WaitForExit();

then start the process on a different thread and let that thread fire an event after process.WaitForExit(); is done.


You should first start the process using the ProcessStartInfo you've just created like:

Process process = Process.Start(psi);

then you can use process.HasExited to check if the process has exited. Often, you don't need to do this, as process.WaitForExit() blocks the code until process exits.


I'm a bit unsure of the scenario from your question... but 4 techniques you can use are:

  • if you have started the process using var process = Process.Start(psi); then:

    • you can periodically check process.HasExited - http://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited.aspx
    • or you can subscribe to Process.Exited - http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx
    • or you can block on Process.WaitForExit - http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforexit.aspx
  • if your process is started in some other way and has some unique name, then you can inspect the enumeration returned by System.Diagnostics.Process.GetProcesses() to determine if your batch process is currently running.

In general... I'd prefer to use Process.Exited, but the other methods all have their place too!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜