Process sometimes hangs while waiting for Exit

前端 未结 4 1219
天命终不由人
天命终不由人 2021-01-11 10:23

What may be the reason of my process hanging while waiting for exit?

This code has to start powershell script which inside performs many action e.g start recompiling

4条回答
  •  -上瘾入骨i
    2021-01-11 10:26

    The problem is that if you redirect StandardOutput and/or StandardError the internal buffer can become full.

    To solve the issues aforementioned you can run the process in separate threads. I do not use WaitForExit, I utilize the process exited event which will return the ExitCode of the process asynchronously ensuring it has completed.

    public async Task RunProcessAsync(params string[] args)
        {
            try
            {
                var tcs = new TaskCompletionSource();
    
                var process = new Process
                {
                    StartInfo = {
                        FileName = 'file path',
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        Arguments = "shell command",
                        UseShellExecute = false,
                        CreateNoWindow = true
                    },
                    EnableRaisingEvents = true
                };
    
    
                process.Exited += (sender, args) =>
                {
                    tcs.SetResult(process.ExitCode);
                    process.Dispose();
                };
    
                process.Start();
                // Use asynchronous read operations on at least one of the streams.
                // Reading both streams synchronously would generate another deadlock.
                process.BeginOutputReadLine();
                string tmpErrorOut = await process.StandardError.ReadToEndAsync();
                //process.WaitForExit();
    
    
                return await tcs.Task;
            }
            catch (Exception ee) {
                Console.WriteLine(ee.Message);
            }
            return -1;
        }
    

    The above code is battle tested calling FFMPEG.exe with command line arguments. I was converting mp4 files to mp3 files and doing over 1000 videos at a time without failing. Unfortunately I do not have direct power shell experience but hope this helps.

提交回复
热议问题