使用 (f.ex.) 按钮停止 C# 中的连续事件

Stopping a continuous Event in C# with (f.ex.) a button

这可能很简单,问题可能不是很好,但我正在寻找完成此任务的最佳或最有效的方法:

  1. 单击按钮会启动一个事件,然后 运行 是一种连续 ping 一个 IP 地址的方法。 ping 输出显示在文本框中。

  2. 点击同一个按钮停止 ping 任务。

这是(我认为的)相关代码:

连接到 Ping 按钮的事件的方法运行:

private void pingClicked (object sender, EventArgs e) {
    pinger();
}

pinger() 方法:

private void pinger() {
    string command = "/c ping " + ipadrtextbox.Text;

    if (contchkbox.Checked) {
        command += " -t";
    }

    ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);

    Process proc = new Process();
    proc.StartInfo = procStartInfo;
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.Start();
    procStartInfo.CreateNoWindow = true;
    procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    proc.OutputDataReceived += new 
    DataReceivedEventHandler(proc_OutputDataReceived);

    proc.Start();

    proc.BeginOutputReadLine();

    procStartInfo.CreateNoWindow = true;
    procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}

void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) {
    if (e.Data != null) {
        string newLine = e.Data.Trim() + Environment.NewLine;
        MethodInvoker append = () => pingoutput.AppendText(newLine);
        pingoutput.BeginInvoke(append);
    }

}

pinger 方法中的 while 循环导致 "An async read operation has already been started on the stream." 的投诉,因此这显然不是正确的方法。

此外,我还没有找到一种方法让该方法在应用程序的其他地方侦听按钮按下,然后使用 roc.CancelOutputRead() 停止任务。但我希望任务应该以这种方式停止?

将 运行 进程保留为 class 的 private 成员然后:

private void pingClicked (object sender, EventArgs e) {
     if( process != null && !process.HasExited )
     {
         process.CancelOutputRead()
         process.Kill();
         process=null;
     } else {
            pinger();
     }
 }