我遇到进程停止的问题。
我尝试了一个代码但它的查杀程序没有停止进程。
示例:
我尝试ping 127.0.0.1及其启动无限ping(-t),我需要停止进程,但它只是杀了它。
如果我点击“停止!”程序停止并关闭。
我的代码:
namespace PingProgramm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread th;
private void button1_Click(object sender, EventArgs e)
{
th = new Thread(thread1);
th.Start();
}
public void thread1()
{
try
{
string command = "/c ping -t " + textBox1.Text;
ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);
Process proc = new Process();
proc.StartInfo = procStartInfo;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
catch (Exception)
{
//if an error occurs with in the try block, it will handled here.
}
}
void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (stop)
{
// sender is our process instance
// so we can cast that safely here
var proc = (Process)sender;
// brutally kill it
proc.Pause();
// or more gently, send a ctrl+C
// http://stackoverflow.com/a/285041/578411
proc.StandardInput.Pause();
}
if (e.Data != null)
{
string newLine = e.Data.Trim() + Environment.NewLine;
MethodInvoker append = () => richTextBox1.Text += newLine;
richTextBox1.BeginInvoke(append);
}
}
bool firstTime = true;
private void textBox1_Click(object sender, EventArgs e)
{
if (firstTime)
{
firstTime = false;
textBox1.Clear();
}
}
bool stop = false;
private void button2_Click(object sender, EventArgs e)
{
stop = true;
}
}
}
祝福,
KLDesigns
答案 0 :(得分:1)
我将您的代码复制并粘贴到VS中并使用以下更改使其工作:
首先,注释掉或删除" proc.WaitForExit();"在thread1定义中...这不是你等待线程退出的地方,而且它似乎导致了问题。
接下来,将proc_OutputDataReceived更改为以下内容:
50px * 2 = 100px height
通过这些更改,您可以停止ping请求,然后重新启动新请求。