1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

別スレッドで立ち上げたProcessをメインスレッドでKillする

Last updated at Posted at 2018-02-13

当たり前かもしれないが、別スレッドで設定して立ち上げたプロセスは、参照を持ってればメインスレッドからKillできる。

    class Program
    {
        static private string defaultAppPath = "C:\\Path\\To\\App\\InfiniteLoop.exe";

        static void Main(string[] args)
        {
            //5スレッド使う
            List<Task> tasks = new List<Task>(5);
            List<Process> processes = new List<Process>(5);
            for(int i=0; i<5; i++)
            {
                Process newProcess = new Process();
                var task = Task.Factory.StartNew(() => RunLoopApp(newProcess));
                tasks.Add(task);
                processes.Add(newProcess);
            }
            
            System.Threading.Thread.Sleep(20000);

            for (int i=0; i<5; i++)
            {
                processes[i].Kill();
                tasks.RemoveAt(i);
            }
        }

        static private void RunLoopApp(Process process)
        {
            process.StartInfo.FileName = defaultAppPath;
            process.Start();
            return;
        }
    }

これはなんらかの理由で、別スレッドで動くプロセスをメイン側でkillしたいときに使えそう。

2018/2/14 追記
上のprocessesリストはスレッドセーフではないので、System.Collections.Concurrentのコレクションを使って対応したほうが良いかも。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?