コンソールアプリで起動した別プロセスを殺す
作ろうと思った理由
コンソールから起動した別プロセスがダイアログを表示したまま、プロセスが終わるまで待っていてメインプロセスがフリーズしてしまった。
一定時間起動した別プロセスが終了しなかったら殺したい。
イメージ図
ソースコード
メモ帳を起動してから、1分以内に終了しなかったら、メモ帳を殺して終了する
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleProcessWaitEnd
{
class Program
{
private const int MAX_SECCONDS = 10 * 1000;
static void Main(string[] args)
{
ProcessStartInfo psiNotepad = new ProcessStartInfo();
psiNotepad.FileName = @"notepad";
Process psNotepad = System.Diagnostics.Process.Start(psiNotepad);
if(!psNotepad.WaitForExit(MAX_SECCONDS))
{
psNotepad.Kill();
}
}
}
}
何分間か動かなかったら時々警告を出すようにするならThreadにする必要がある。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace ConsoleThread
{
class Program
{
private const int MAX_SECCONDS = 60;
static private int timerCount = 0;
static private bool isSuccess = false;
static private Process psNotepad;
static void Main(string[] args)
{
Thread thexe = new Thread(new ThreadStart(ThreadExe));
thexe.Start();
while (true)
{
if (isSuccess)
{
Console.WriteLine("OK");
break;
}
if (timerCount < MAX_SECCONDS)
{
Thread.Sleep(1000);
timerCount++;
}
else
{
Console.WriteLine("NG");
psNotepad.Kill();
thexe.Abort();
break;
}
}
Console.ReadKey();
}
private static void ThreadExe()
{
ProcessStartInfo psiNotepad = new ProcessStartInfo();
psiNotepad.FileName = @"notepad";
psNotepad = System.Diagnostics.Process.Start(psiNotepad);
psNotepad.WaitForExit();
isSuccess = true;
}
}
}