Как в C# создать дочерний процесс, который используется несколькими методами, а затем уничтожить его?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public Process myprocess;
        public StreamWriter mywriter;
        public StreamReader myreader;

        // асинхронно посылает на вход myConsoleApp.exe
        private async void MyWriteAsync(string cm)
        {
            await mywriter.WriteLineAsync(cm);
        }

        // постоянно ожидает ответ от myConsoleApp.exe, 
        // полученные строки пишет в textBox1
        private async void MyReadAsync()
        {
            string output;
            do
            {
                output = await myreader.ReadLineAsync();
                textBox1.Text += output + "\r\n";
                textBox1.Select(textBox1.Text.Length, 0);
                textBox1.ScrollToCaret();
            } while (output != null);
        }

        // запуск дочернего процесса myConsoleApp.exe
        private void Button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "ok\r\n";

            using (myprocess = new Process())
            {
                myprocess.StartInfo.FileName = "myConsoleApp.exe";
                myprocess.StartInfo.UseShellExecute = false;
                myprocess.StartInfo.CreateNoWindow = true;
                myprocess.StartInfo.RedirectStandardInput = true;
                myprocess.StartInfo.RedirectStandardOutput = true;
                myprocess.Start();

                mywriter = myprocess.StandardInput;
                myreader = myprocess.StandardOutput;

                mywriter.WriteLine("hello");
                MyReadAsync();
            }
        }

        // отправить команду из textBox2 на вход myConsoleApp.exe
        private void Button2_Click(object sender, EventArgs e)
        {
            string cm = textBox2.Text;
            textBox1.Text += cm + "\r\n";
            textBox1.Select(textBox1.Text.Length, 0);
            textBox1.ScrollToCaret();
            MyWriteAsync(cm);
        }

        // при закрытии окна завершить дочерний процесс 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            myprocess.Close();
        }
    }
}


Пытался так, но после завершения приложения дочерний процесс myConsoleApp.exe не завершается, а продолжает работать сам по себе как зомби.
  • Вопрос задан
  • 827 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы