Skip to content

Commit

Permalink
This has been part of .NET since 5
Browse files Browse the repository at this point in the history
  • Loading branch information
jnm2 committed Aug 12, 2023
1 parent 7629aba commit c357343
Showing 1 changed file with 0 additions and 74 deletions.
74 changes: 0 additions & 74 deletions src/YouTubeDownloadTool/Utils/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Interop;

Expand All @@ -26,77 +23,6 @@ public static WinErrorCode GetErrorCode(this Exception exception)
return (WinErrorCode)exception.HResult;
}

public static ProcessExitAwaitable WaitForExitAsync(this Process process)
{
return new ProcessExitAwaitable(process);
}

public readonly struct ProcessExitAwaitable
{
private readonly Process process;

public ProcessExitAwaitable(Process process)
{
this.process = process ?? throw new ArgumentNullException(nameof(process));
}

public ProcessExitAwaiter GetAwaiter() => new(process);

public readonly struct ProcessExitAwaiter : ICriticalNotifyCompletion
{
private readonly Process process;

public ProcessExitAwaiter(Process process)
{
this.process = process ?? throw new ArgumentNullException(nameof(process));
}

public bool IsCompleted => process.HasExited;

public void OnCompleted(Action continuation)
{
if (continuation is null) return;

var closure = new OnCompletedClosure(continuation);

process.EnableRaisingEvents = true;
process.Exited += closure.OnProcessExited;
if (process.HasExited) closure.InvokeContinuation();
}

private sealed class OnCompletedClosure
{
private Action? continuation;

public OnCompletedClosure(Action continuation)
{
this.continuation = continuation;
}

public void OnProcessExited(object? sender, EventArgs e)
{
InvokeContinuation();
}

public void InvokeContinuation()
{
Interlocked.Exchange(ref continuation, null)?.Invoke();
}
}

public void UnsafeOnCompleted(Action continuation)
{
OnCompleted(continuation);
}

public void GetResult()
{
if (!process.HasExited)
throw new InvalidOperationException("GetResult may only be called after IsCompleted returns true or OnCompleted invokes a callback.");
}
}
}

public static System.Windows.Forms.DialogResult ShowDialog(this System.Windows.Forms.CommonDialog dialog, Window owner)
{
return dialog.ShowDialog(owner.AsWindowsFormsWindow());
Expand Down

0 comments on commit c357343

Please sign in to comment.