Skip to content
This repository was archived by the owner on Nov 11, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions WSLDiskShrinker/Common/ProcessExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,24 @@ namespace WSLDiskShrinker.Common;
// https://stackoverflow.com/questions/470256/process-waitforexit-asynchronously
static class ProcessExtension
{
/// <summary>
/// Waits asynchronously for the process to exit.
/// </summary>
/// <param name="process">The process to wait for cancellation.</param>
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return
/// immediately as canceled.</param>
/// <returns>A Task representing waiting for the process to end.</returns>
public static Task CustomWaitForExitAsync(this Process process,
CancellationToken cancellationToken = default)
{
if (process.HasExited) return Task.CompletedTask;
/// <summary>
/// Waits asynchronously for the process to exit.
/// </summary>
/// <param name="process">The process to wait for cancellation.</param>
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return
/// immediately as canceled.</param>
/// <returns>A Task representing waiting for the process to end.</returns>
public static Task CustomWaitForExitAsync(this Process process,
CancellationToken cancellationToken = default)
{
if (process.HasExited) return Task.CompletedTask;

var tcs = new TaskCompletionSource<object>();
process.EnableRaisingEvents = true;
process.Exited += (sender, args) => tcs.TrySetResult(null);
if (cancellationToken != default)
cancellationToken.Register(() => tcs.SetCanceled());
var tcs = new TaskCompletionSource<object>();
process.EnableRaisingEvents = true;
process.Exited += (sender, args) => tcs.TrySetResult(process.ExitCode);
if (cancellationToken != default)
cancellationToken.Register(() => tcs.SetCanceled());

return process.HasExited ? Task.CompletedTask : tcs.Task;
}
return process.HasExited ? Task.CompletedTask : tcs.Task;
}
}

Loading