If I kill a System.Diagnostics.Process with .Kill(), do I also need to call .Close()?

后端 未结 2 1574
你的背包
你的背包 2021-02-18 17:36

Using C# 4.0, I\'ve created a System.Diagnostics.Process that I expect to take a short amount of time to run. If for some reason the process hasn\'t exited after so

2条回答
  •  半阙折子戏
    2021-02-18 18:20

    System.Diagnostics.Process implements IDisposable via the Component class, and the protected Dispose(bool) method calls Close(). It is generally considered good practice to dispose of disposable resources when you are done with them, as this will immediately release any resources associated with the class (not having to wait for the GC to run).

    So to answer your question:

    Yes, please call Close() by calling the Dispose() method directly or via the C# using construct as follows.

    using(Process proc = CreateProcess())
    {
        StartProcess(proc);
        if (!proc.WaitForExit(timeout))
        {
            proc.Kill();
        }
    }
    

提交回复
热议问题