Process.Close 方法

定义

释放与此组件关联的所有资源。

C#
public void Close ();

示例

以下示例启动记事本的实例。 然后,它以 2 秒的间隔检索关联进程的物理内存使用情况,最长为 10 秒。 该示例检测进程是否在 10 秒前退出。 如果进程在 10 秒后仍在运行,该示例将关闭该进程。

C#
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace ProcessSample
{
    class MyProcessClass
    {
        public static void Main()
        {
            try
            {
                using (Process myProcess = Process.Start("Notepad.exe"))
                {
                    // Display physical memory usage 5 times at intervals of 2 seconds.
                    for (int i = 0; i < 5; i++)
                    {
                        if (!myProcess.HasExited)
                        {
                            // Discard cached information about the process.
                            myProcess.Refresh();
                            // Print working set to console.
                            Console.WriteLine($"Physical Memory Usage: {myProcess.WorkingSet}");
                            // Wait 2 seconds.
                            Thread.Sleep(2000);
                        }
                        else
                        {
                            break;
                        }
                    }

                    // Close process by sending a close message to its main window.
                    myProcess.CloseMainWindow();
                    // Free resources associated with process.
                    myProcess.Close();
                }
            }
            catch (Exception e) when (e is Win32Exception || e is FileNotFoundException)
            {
                Console.WriteLine("The following exception was raised: ");
                Console.WriteLine(e.Message);
            }
        }
    }
}

注解

方法 Close 使进程停止等待退出(如果它正在等待),关闭进程句柄,并清除特定于进程的属性。 Close 在外部引用标准输出、输入和错误读取器和编写器时,不会关闭它们。

备注

Dispose 方法调用 Close。 将 Process 对象置于 块中 using 可以释放资源,而无需调用 Close

适用于

产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1