Awaitable 0.3.1

dotnet add package Awaitable --version 0.3.1                
NuGet\Install-Package Awaitable -Version 0.3.1                
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.3.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Awaitable --version 0.3.1                
#r "nuget: Awaitable, 0.3.1"                
#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.3.1

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

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.3.x Target more frameworks to reduce package dependency graph
0.2.0 Fix .csproj and align language features with target framework
0.1.2 Improve documentation
0.1.1 Strongly name assembly
0.1.0 Initial release
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  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 is compatible.  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 is compatible.  netstandard1.2 is compatible.  netstandard1.3 is compatible.  netstandard1.4 is compatible.  netstandard1.5 is compatible.  netstandard1.6 is compatible.  netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net45 is compatible.  net451 is compatible.  net452 is compatible.  net46 is compatible.  net461 is compatible.  net462 is compatible.  net463 was computed.  net47 is compatible.  net471 is compatible.  net472 is compatible.  net48 is compatible.  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.
  • .NETFramework 4.5

    • No dependencies.
  • .NETFramework 4.5.1

    • No dependencies.
  • .NETFramework 4.5.2

    • No dependencies.
  • .NETFramework 4.6

    • No dependencies.
  • .NETFramework 4.6.1

    • No dependencies.
  • .NETFramework 4.6.2

    • No dependencies.
  • .NETFramework 4.7

    • No dependencies.
  • .NETFramework 4.7.1

    • No dependencies.
  • .NETFramework 4.7.2

    • No dependencies.
  • .NETFramework 4.8

    • No dependencies.
  • .NETStandard 1.0

  • .NETStandard 1.1

  • .NETStandard 1.2

  • .NETStandard 1.3

  • .NETStandard 1.4

  • .NETStandard 1.5

  • .NETStandard 1.6

  • .NETStandard 2.0

    • No dependencies.
  • .NETStandard 2.1

    • No dependencies.
  • net5.0

    • No dependencies.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.

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,253 12/8/2022
0.3.0 474 12/8/2022
0.2.0 304 12/7/2022
0.1.2 425 6/23/2022