简体   繁体   中英

C# - Kill a threaded process from a button_click

I'm trying to kill notepad.exe using a button click event.

It need to be in a thread because of the process.WaitForExit();

Right now, the button click does nothing at all, can't figure out why.

Thanks in advance for your help :)

Here is my current code:

using System.Windows;
using System.Threading;
using System.Diagnostics;


namespace WpfApp5
{
    public partial class MainWindow : Window
    {
        Thread mythread = new Thread(() =>
        {
            Process process = new Process();
            process.StartInfo.FileName = @"notepad.exe";
            process.Start();
            process.WaitForExit();
        });

        public MainWindow()
        {
            InitializeComponent();
            mythread.Start();   
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            mythread.Abort();
        }
    }
}
  1. You don't need the thread. You're already starting a separate process, which has its own set of threads.
  2. All you need to do is hang onto process (eg as a member variable) and kill it.

For example:

public partial class MainWindow : Window
{
    private Process _process = null;

    public MainWindow()
    {
        InitializeComponent();
        _process = new Process();
        _process.StartInfo.FileName = @"notepad.exe";
        _process.Start();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        if (_process == null) return;
        _process.Kill();
        _process = null;
    }
}

With minimum change in your code, you can do it like below,

public partial class MainWindow : Window
{
    static Process process; //making process class level member;
    Thread mythread = new Thread(() =>
    {
        process = new Process();
        process.StartInfo.FileName = @"notepad.exe";
        process.Start();
    });

    public MainWindow()
    {
        InitializeComponent();
        mythread.Start();   
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        process.Kill(); //killing the actual process.
        mythread.Abort();
    }
}

Your application (and thread) runs in its own process separate from the one you started. Killing the thread in your process won't kill the other process. You need to look at System.Diagnostics.Process.Kill()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM