应用程序在进程退出事件时退出
本文关键字:退出 出事件 进程 应用程序 | 更新日期: 2023-09-27 18:19:29
我正在制作表单应用程序,它也在不同的线程上运行控制台进程。基本上,我需要在应用程序退出后取消阻止按钮。在我制作事件处理程序之前,完成后的进程刚刚停止,但现在,在事件之后,应用程序本身被杀死了。
以下是使进程运行的代码:
public void CallConsole()//This Calls the console application
{
Thread.CurrentThread.IsBackground = true;
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = filename;
if (checkBox1.Checked)
p.StartInfo.CreateNoWindow = true;
p.EnableRaisingEvents = true;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.Exited += new EventHandler(p_Exited);
p.Disposed += new EventHandler(p_Exited);
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
}
我尝试使用Thread.IsBackground属性,但这并没有改变任何东西
下面是事件处理程序本身:
void p_Exited(object sender, EventArgs e)//Process on exit or disposed will make button1 avalable
{
button1.Enabled = true;
}
任何想法为什么添加后的应用程序
p.EnableRaisingEvents = true;
现在被杀了,不仅仅是过程?
这里的问题是
void p_Exited(object sender, EventArgs e)//Process on exit or disposed will make button1 available
{
button1.Enabled = true;
}
需要调用,并且没有任何错误处理。一旦我添加了另一个检查button1.InvokeRequired
的函数,如果它确实通过调用再次调用自己,它的效果很好
这里的问题是 Exited
事件在线程池线程上触发。只能在 UI 线程上修改控件。
您可以调用 BeginInvoke
,但通过设置将Process
对象配置为调用自身更简单:
p.SynchronizingObject = button1;
Button
实现ISynchronizeInvoke
,Process
对象用它来调用其事件。