private static Dictionary <string, string> _ReadEnv(ProcessBinaryReader br)
        {
            // Environment variables are case insensitive on Windows
            var env = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            while (true)
            {
                var s = br.ReadCString();
                if (s.Length == 0)
                {
                    // End of environment block.
                    break;
                }

                int j = s.IndexOf('=');
                if (j <= 0)
                {
                    continue;
                }

                string name  = s.Substring(0, j);
                string value = s.Substring(j + 1);

                env[name] = value;
            }

            return(env);
        }
        private static Dictionary <string, string> _ReadVariablesCore(Process process)
        {
            int retryCount = 5;

            bool RetryPolicy() => -- retryCount > 0;

Again:
            try
            {
                var stream = _GetEnvStream(process.Handle);
                var reader = new ProcessBinaryReader(new BufferedStream(stream), Encoding.Unicode);
                var env    = _ReadEnv(reader);

                if (env.Count == 0)
                {
                    // Empty environment may indicate that a process environment block has not been initialized yet.
                    if (RetryPolicy())
                    {
                        goto Again;
                    }
                }

                return(env);
            }
            catch (EndOfStreamException ex)
            {
                if (process.HasExited)
                {
                    throw new InvalidOperationException("The target process has exited", ex);
                }

                // There may be a race condition in environment block initialization of a recently started process.
                if (RetryPolicy())
                {
                    Thread.Sleep(1000);
                    goto Again;
                }
                else
                {
                    throw;
                }
            }
        }