0

Process.Start hangs in linux. I am generating a C# file from proto file. It runs fine on some files but hangs once in a while. This method is being run on a separate thread.

    public async Task GenerateCSharpFileAsync(string fileName, string protoFilePath, params string[] args)
    {
        var outputFolder = ""; // some path
        var protocPath = GetProtoCompiler();
        var inputs = $" --proto_path={protoFilePath} --csharp_out={outputFolder} --error_format=gcc {fileName} {string.Join(" ", args)}";

        var psi = new ProcessStartInfo(
            protocPath,
            arguments: inputs
        )
        {
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            WorkingDirectory = Global.WebRoot,
            UseShellExecute = false
        };

        psi.RedirectStandardOutput = psi.RedirectStandardError = true;

        var proc = new Process { StartInfo = psi };

        try
        {
            proc.Start();

            await proc.WaitForExitAsync();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            proc.Close();
            proc.Dispose();
        }
    }

WaitForExitAsync() is being referenced from here: process.WaitForExit() asynchronously

Code for waitforexitasync:

    public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
    {
        var tcs = new TaskCompletionSource<bool>();

        void ProcessExited(object sender, EventArgs e)
        {
            Task.Run(() => tcs.TrySetResult(true));
        }

        process.EnableRaisingEvents = true;
        process.Exited += ProcessExited;

        try
        {
            if (process.HasExited)
            {
                return;
            }

            using (cancellationToken.Register(() => Task.Run(() => tcs.TrySetCanceled(), cancellationToken)))
            {
                await tcs.Task;
            }
        }
        finally
        {
            process.Exited -= ProcessExited;
        }
    }

Kindly assist.

Gauravsa
  • 6,330
  • 2
  • 21
  • 30

1 Answers1

1

For some reason if the Service is run from command line like: dotnet "Test.dll" & as a background task, it simply hangs.

Tried running dotnet "Test.dll" without the & and it works fine.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Gauravsa
  • 6,330
  • 2
  • 21
  • 30