Search code examples
c#.net.net-6.0

Forcing timeout on a process in .NET 6


I come from a C background, and my knowledge of C# and .NET is very very limited.

Now, I am running an executable in my code as a Process, in a .NET 6.0 application. This is what the code looks like

static string ExternalExe(string input)
{
    string output = string.Empty;

    ProcessStartInfo info = new()
    {
        FileName               = "path_here",
        Arguments              = input,
        RedirectStandardOutput = true,
        UseShellExecute        = false
    };

    using (Process? process = Process.Start(info))
    {
        if (process != null)
        {
            output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
        }
        else
        {
            throw new CustomException();
        }
    }

    return output;
}

I want to implement a timeout for this. As in, if the process takes, for example, more than 1 second to exit, it should generate an exception or something like that. How would I implement that?

Any help would be much appreciated, and thanks in advance. :)


Solution

  • You could use the WaitForExit(TimeSpan) but this will block your UI thread. Since we're in .NET6 I would use the asynchronous version with a CancellationTokenSource set to automatically cancel after x ms.

    await process.WaitForExitAsync(new CancellationTokenSource(3000).Token);