Awaitable 0.1.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Awaitable --version 0.1.2                
NuGet\Install-Package Awaitable -Version 0.1.2                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Awaitable" Version="0.1.2" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Awaitable --version 0.1.2                
#r "nuget: Awaitable, 0.1.2"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Awaitable as a Cake Addin
#addin nuget:?package=Awaitable&version=0.1.2

// Install Awaitable as a Cake Tool
#tool nuget:?package=Awaitable&version=0.1.2                

Awaitable

Interfaces for custom awaitable expressions.

GitHub Workflow Status

Nuget

Examples

A few examples to get your creative juices flowing:

Awaitable TimeSpan

Turn any TimeSpan into a timer that returns itself after its amount of time passes:

using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

readonly record struct TimeSpanAwaiter(TaskAwaiter TaskAwaiter, TimeSpan TimeSpan) : IAwaiter<TimeSpan>
{
    public TimeSpan GetResult()
    {
        TaskAwaiter.GetResult();
        return TimeSpan;
    }

    public void OnCompleted(Action continuation) => TaskAwaiter.OnCompleted(continuation);

    public void UnsafeOnCompleted(Action continuation) => TaskAwaiter.UnsafeOnCompleted(continuation);

    public bool IsCompleted => TaskAwaiter.IsCompleted;
}

static class TimeSpanExtensions
{
    public static TimeSpanAwaiter GetAwaiter(this TimeSpan timeSpan) => new(Task.Delay(timeSpan).GetAwaiter(), timeSpan);
}

[Fact]
public async Task ShouldYieldToSynchronizationContext()
{
    var timeSpan = TimeSpan.FromSeconds(1);
    var result = await timeSpan; // Takes 1 second to evaluate
    Assert.Equal(timeSpan, result);
}

A simpler variation of this can be found here:<br/> https://devblogs.microsoft.com/pfxteam/await-anything/#:~:text=1%2Dline%20GetAwaiter%20method%20for%20TimeSpan

Awaitable CancellationToken

Await the cancellation of any CancellationToken. A slight tweak will make this work for any WaitHandle:

using System;
using System.Threading;

readonly record struct WaitHandleAwaiter(WaitHandle? Handle) : IAwaiter
{
    static readonly ContextCallback InvokeActionContextCallback = state => ((Action)state!)();
    static readonly WaitOrTimerCallback InvokeActionWaitOrTimerCallback = (state, _) => ((Action)state!)();

    public bool IsCompleted => Handle?.WaitOne(0) ?? false;

    public void GetResult()
    {}

    public void OnCompleted(Action continuation)
    {
        var context = ExecutionContext.Capture();
        if (context is not null)
        {
            void WrappedContinuation() => ExecutionContext.Run(context, InvokeActionContextCallback, continuation);
            UnsafeOnCompleted(WrappedContinuation);
        }
        else
        {
            UnsafeOnCompleted(continuation);
        }
    }

    public void UnsafeOnCompleted(Action continuation)
    {
        if (Handle is null)
            return; // Missing handle is treated the same as an infinite wait. The continuation will never execute
        ThreadPool.RegisterWaitForSingleObject(
            Handle,
            InvokeActionWaitOrTimerCallback,
            continuation,
            Timeout.Infinite,
            true
        );
    }
}

static class CancellationTokenExtensions
{
    public static WaitHandleAwaiter GetAwaiter(this CancellationToken cancellationToken) =>
        cancellationToken.CanBeCanceled
            ? new WaitHandleAwaiter(cancellationToken.WaitHandle)
            : default;
}

[Fact]
public async Task ShouldAwaitCancellation()
{
    var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
    var token = cts.Token;
    await token; // Takes 1 second to evaluate
}

Synchronously return 42

Jump through a lot of hoops to synchronously return a constant from an awaitable expression:

using System;
using System.Threading;

sealed class Awaiter<T> : IAwaiter<T>
{
    static readonly ContextCallback ExecuteContinuation = state => ((Action)state!)();

    readonly Func<T> _getResult;
    readonly Func<bool> _isCompleted;
    readonly Action<Action> _unsafeOnCompleted;

    public Awaiter(
        Func<T> getResult,
        Func<bool> isCompleted,
        Action<Action> unsafeOnCompleted)
    {
        _getResult = getResult;
        _isCompleted = isCompleted;
        _unsafeOnCompleted = unsafeOnCompleted;
    }

    public bool IsCompleted => _isCompleted();

    public T GetResult() => _getResult();

    public void OnCompleted(Action continuation)
    {
        var context = ExecutionContext.Capture();
        if (context is not null)
        {
            void WrappedContinuation() => ExecutionContext.Run(context, ExecuteContinuation, continuation);
            UnsafeOnCompleted(WrappedContinuation);
        }
        else
        {
            UnsafeOnCompleted(continuation);
        }
    }

    public void UnsafeOnCompleted(Action continuation) => _unsafeOnCompleted(continuation);
}

record Awaitable<T>(Awaiter<T> Awaiter) : IAwaitable<T, Awaiter<T>>
{
    public Awaiter<T> GetAwaiter() => Awaiter;
}

[Fact]
public async Task ShouldBeFortyTwo()
{
    var awaitableFortyTwo = new Awaitable<int>(new Awaiter<int>(
        getResult: () => 42,
        isCompleted: () => true, // Tell compiler not to bother passing us a continuation
        unsafeOnCompleted: _ => throw new NotImplementedException()
    ));
    Assert.Equal(42, await awaitableFortyTwo);
}

Release history

Version Notes
0.1.0 Initial release
0.1.1 Strongly name assembly
0.1.2 Improve documentation
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp1.0 was computed.  netcoreapp1.1 was computed.  netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard1.0 is compatible.  netstandard1.1 was computed.  netstandard1.2 was computed.  netstandard1.3 was computed.  netstandard1.4 was computed.  netstandard1.5 was computed.  netstandard1.6 was computed.  netstandard2.0 was computed.  netstandard2.1 was computed. 
.NET Framework net45 was computed.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen30 was computed.  tizen40 was computed.  tizen60 was computed. 
Universal Windows Platform uap was computed.  uap10.0 was computed. 
Windows Phone wp8 was computed.  wp81 was computed.  wpa81 was computed. 
Windows Store netcore was computed.  netcore45 was computed.  netcore451 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Awaitable:

Package Downloads
ReentrantAsyncLock

A reentrant asynchronous lock

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.3.1 3,185 12/8/2022
0.3.0 468 12/8/2022
0.2.0 300 12/7/2022
0.1.2 419 6/23/2022