如何在进程被杀死时释放资源 [英] How I can deallocate resources when the process gets killed

查看:364
本文介绍了如何在进程被杀死时释放资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉这个微不足道的问题。当进程被例如任务管理器杀死时,如何释放资源?有没有办法在进程关闭之前调用函数?在此先感谢您的回答。我想我会按照建议实现一个看门狗进程。

解决方案





如果你使用Windows表单,然后您可以使用 Form.FormClosing [< a href =http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspxtarget =_ blanktitle =New Window> ^ ]事件:

  void  Form1_FormClosing( object  sender,FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.TaskManagerClosing)
{
// 任务管理器正在关闭应用程序
}
else if (e.CloseReason == CloseReason.WindowsShutDown)
{
// 应用程序已关闭,因为Windows正在关闭
}
else if (e.CloseReason == CloseReason.UserClosing)
{
// 用户关闭表单
}
其他
{
// 其他原因
}
}



在这里你会找到 CloseReason 枚举的所有枚举字段: http://msdn.microsoft.com/en-us/library/system.windows.forms .closereason.aspx [ ^ ]

如果您使用WPF,请使用 Window.Closing [ ^ ]事件。

但是如果是任务管理器关闭应用程序,然后仅当用户单击结束任务按钮时才会调用该函数。单击结束任务按钮类似于 Process.Close [ ^ ] 方法。如果用户单击结束进程按钮,则进程将立即停止,然后您无法释放资源。单击结束进程按钮类似于 Process.Kill方法 [ ^ ]



希望这有帮助。


您是否尝试过捕获由Windows引发的WM_CLOSE事件?



有一篇关于处理此此处<的外部文章/ A>

I''m sorry for the trivial question. How I can deallocate resources when the process gets killed by, for example, the Task Manager? Is there a way to call a function before the process gets closed? Thanks in advance Thanks to all for your answers. I think I will implement a watchdog process as suggested.

解决方案

Hi,

If you use Windows Forms, then you can use the
Form.FormClosing[^] event:

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.TaskManagerClosing)
    {
        // Task Manager is closing the application
    }
    else if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        // application is closed because Windows is shutting down
    }
    else if (e.CloseReason == CloseReason.UserClosing)
    {
        // user closes the form
    }
    else
    {
       // other reason
    }
}


Here you''ll find all enum fields of the CloseReason enum: http://msdn.microsoft.com/en-us/library/system.windows.forms.closereason.aspx[^]
If you use WPF, use the Window.Closing[^] event.
But if Task Manager closes the application, then the function will be called only if the user clicks on the "End Task" button. Clicking on the "End Task" button is similar to the Process.Close[^] method. If the user clicks on the "End Process" button, then the process will be stopped immediately, then you can''t deallocate resources. Clicking on the "End Process" button is similar to the Process.Kill method[^]

Hope this helps.


Have you tried capturing the WM_CLOSE event which is raised by Windows?

There is an external article on handling this here


这篇关于如何在进程被杀死时释放资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆