簡體   English   中英

當應用程序在C#中關閉時,如何自動關閉由應用程序啟動的進程?

[英]How to automatically close the process that is started by application, when application closes in c#?

我遇到了由我的C#應用​​程序啟動的進程的有線問題,在我的應用程序中,我啟動了一個運行ffmpeg命令的進程,該命令執行得很好,但是無論如何,如果我關閉我的應用程序,則該進程仍會繼續執行。

    private static bool RunRecordProcess(string command)
    {
        Process process = new Process();
        try
        {                
            ProcessStartInfo processStartInfo = new 
            ProcessStartInfo(Application.StartupPath + 
            FFMPEG_EXE_FILE_PATH);
            processStartInfo.UseShellExecute = false;
            processStartInfo.Arguments = "-hide_banner -loglevel 8 " + 
            command;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            processStartInfo.CreateNoWindow = true;
            processStartInfo.Verb = "";

            process.EnableRaisingEvents = true;
            process.StartInfo = processStartInfo;
            process.Start();               
            string error = process.StandardError.ReadToEnd();
            if (error.Length > 0)
            {
                if (!process.HasExited)
                {
                    process.Kill();
                    //throw new Exception("Failure some error occured");
                }
            }
            process.WaitForExit();
        }   
        catch(Exception ex)
        {
            process.Kill();
            ExceptionHandler.handleException(ex);
            return false;
        }         
        return true;
    }

我想要的是當我的應用程序退出時,由該應用程序啟動的進程將自動退出,因此不會有無用的進程使用我的系統Cpu。

謝謝!

您應該創建作業對象(kernel32中的CreateJobObject函數)。 還有更多描述:

https://tulisanlain.blogspot.com/2016/08/kill-child-process-when-parent-exit-c.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM