3 people like it.

Awaiting arbitrary C# awaitables

Uses SRTPs to define a general purpose adapter for awaiting arbitrary C# awaitables in F# async workflows.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
open System
open System.Runtime.CompilerServices

// See https://devblogs.microsoft.com/pfxteam/await-anything/ for more details on awaitables/awaiters.

type Async with
    static member inline AwaitCSharpAwaitable< ^TAwaitable, ^TAwaiter, ^TResult when
                                               ^TAwaiter :> ICriticalNotifyCompletion and
                                               ^TAwaitable : (member GetAwaiter : unit -> ^TAwaiter) and
                                               ^TAwaiter : (member IsCompleted : bool) and
                                               ^TAwaiter : (member GetResult : unit -> ^TResult)>
                                               (awaitable : ^TAwaitable) : Async< ^TResult> =

        Async.FromContinuations(fun (sk,ek,_) ->
            let awaiter = (^TAwaitable : (member GetAwaiter : unit -> ^TAwaiter) awaitable)
            let oncompleted () =
                let result =
                    try Ok (^TAwaiter : (member GetResult : unit -> ^TResult) awaiter)
                    with e -> Error e

                match result with
                | Ok t -> sk t
                | Error e -> ek e

            if (^TAwaiter : (member IsCompleted : bool) awaiter) then 
                oncompleted()
            else
                // NB does not flow the execution context
                awaiter.UnsafeOnCompleted(Action oncompleted)
        )

// examples

open System.Threading.Tasks

let x = Async.AwaitCSharpAwaitable(Task.Delay(1000)) |> Async.RunSynchronously
let y = Async.AwaitCSharpAwaitable(new ValueTask()) |> Async.RunSynchronously
let z = Async.AwaitCSharpAwaitable(new ValueTask<_>(42)) |> Async.RunSynchronously
namespace System
namespace System.Runtime
namespace System.Runtime.CompilerServices
Multiple items
type Async =
  static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
  static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
  static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
  static member AwaitTask : task:Task -> Async<unit>
  static member AwaitTask : task:Task<'T> -> Async<'T>
  static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
  static member CancelDefaultToken : unit -> unit
  static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
  static member Choice : computations:seq<Async<'T option>> -> Async<'T option>
  static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
  ...

--------------------
type Async<'T> =
type ICriticalNotifyCompletion =
  inherit INotifyCompletion
  member UnsafeOnCompleted : continuation:Action -> unit
type unit = Unit
type bool = Boolean
val awaitable : 'TAwaitable (requires member GetAwaiter and 'TAwaiter :> ICriticalNotifyCompletion and member get_IsCompleted and member GetResult)
static member Async.FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
val sk : ('TResult -> unit)
val ek : (exn -> unit)
val awaiter : 'TAwaiter (requires 'TAwaiter :> ICriticalNotifyCompletion and member get_IsCompleted and member GetResult)
val oncompleted : (unit -> unit)
[<Struct>]
val result : Result<'TResult,exn>
union case Result.Ok: ResultValue: 'T -> Result<'T,'TError>
val e : exn
union case Result.Error: ErrorValue: 'TError -> Result<'T,'TError>
val t : 'TResult
Multiple items
type Action =
  delegate of unit -> unit

--------------------
type Action<'T> =
  delegate of 'T -> unit

--------------------
type Action<'T1,'T2> =
  delegate of 'T1 * 'T2 -> unit

--------------------
type Action<'T1,'T2,'T3> =
  delegate of 'T1 * 'T2 * 'T3 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10,'T11> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 * 'T11 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10,'T11,'T12> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 * 'T11 * 'T12 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10,'T11,'T12,'T13> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 * 'T11 * 'T12 * 'T13 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10,'T11,'T12,'T13,'T14> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 * 'T11 * 'T12 * 'T13 * 'T14 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10,'T11,'T12,'T13,'T14,'T15> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 * 'T11 * 'T12 * 'T13 * 'T14 * 'T15 -> unit

--------------------
type Action<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'T8,'T9,'T10,'T11,'T12,'T13,'T14,'T15,'T16> =
  delegate of 'T1 * 'T2 * 'T3 * 'T4 * 'T5 * 'T6 * 'T7 * 'T8 * 'T9 * 'T10 * 'T11 * 'T12 * 'T13 * 'T14 * 'T15 * 'T16 -> unit
namespace System.Threading
namespace System.Threading.Tasks
val x : unit
static member Async.AwaitCSharpAwaitable : awaitable:'TAwaitable -> Async<'TResult> (requires member GetAwaiter and 'TAwaiter :> ICriticalNotifyCompletion and member get_IsCompleted and member GetResult)
Multiple items
type Task =
  new : action:Action -> Task + 7 overloads
  member AsyncState : obj
  member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable
  member ContinueWith : continuationAction:Action<Task> -> Task + 19 overloads
  member CreationOptions : TaskCreationOptions
  member Dispose : unit -> unit
  member Exception : AggregateException
  member GetAwaiter : unit -> TaskAwaiter
  member Id : int
  member IsCanceled : bool
  ...

--------------------
type Task<'TResult> =
  inherit Task
  new : function:Func<'TResult> -> Task<'TResult> + 7 overloads
  member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable<'TResult>
  member ContinueWith : continuationAction:Action<Task<'TResult>> -> Task + 19 overloads
  member GetAwaiter : unit -> TaskAwaiter<'TResult>
  member Result : 'TResult
  static member Factory : TaskFactory<'TResult>

--------------------
Task(action: Action) : Task
Task(action: Action, cancellationToken: Threading.CancellationToken) : Task
Task(action: Action, creationOptions: TaskCreationOptions) : Task
Task(action: Action<obj>, state: obj) : Task
Task(action: Action, cancellationToken: Threading.CancellationToken, creationOptions: TaskCreationOptions) : Task
Task(action: Action<obj>, state: obj, cancellationToken: Threading.CancellationToken) : Task
Task(action: Action<obj>, state: obj, creationOptions: TaskCreationOptions) : Task
Task(action: Action<obj>, state: obj, cancellationToken: Threading.CancellationToken, creationOptions: TaskCreationOptions) : Task

--------------------
Task(function: Func<'TResult>) : Task<'TResult>
Task(function: Func<'TResult>, cancellationToken: Threading.CancellationToken) : Task<'TResult>
Task(function: Func<'TResult>, creationOptions: TaskCreationOptions) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj) : Task<'TResult>
Task(function: Func<'TResult>, cancellationToken: Threading.CancellationToken, creationOptions: TaskCreationOptions) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj, cancellationToken: Threading.CancellationToken) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj, creationOptions: TaskCreationOptions) : Task<'TResult>
Task(function: Func<obj,'TResult>, state: obj, cancellationToken: Threading.CancellationToken, creationOptions: TaskCreationOptions) : Task<'TResult>
Task.Delay(millisecondsDelay: int) : Task
Task.Delay(delay: TimeSpan) : Task
Task.Delay(millisecondsDelay: int, cancellationToken: Threading.CancellationToken) : Task
Task.Delay(delay: TimeSpan, cancellationToken: Threading.CancellationToken) : Task
static member Async.RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:Threading.CancellationToken -> 'T
val y : unit
Multiple items
type ValueTask =
  struct
    new : task:Task -> ValueTask + 1 overload
    member AsTask : unit -> Task
    member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredValueTaskAwaitable
    member Equals : obj:obj -> bool + 1 overload
    member GetAwaiter : unit -> ValueTaskAwaiter
    member GetHashCode : unit -> int
    member IsCanceled : bool
    member IsCompleted : bool
    member IsCompletedSuccessfully : bool
    member IsFaulted : bool
    ...
  end

--------------------
type ValueTask<'TResult> =
  struct
    new : result:'TResult -> ValueTask<'TResult> + 2 overloads
    member AsTask : unit -> Task<'TResult>
    member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredValueTaskAwaitable<'TResult>
    member Equals : obj:obj -> bool + 1 overload
    member GetAwaiter : unit -> ValueTaskAwaiter<'TResult>
    member GetHashCode : unit -> int
    member IsCanceled : bool
    member IsCompleted : bool
    member IsCompletedSuccessfully : bool
    member IsFaulted : bool
    ...
  end

--------------------
ValueTask ()
ValueTask(task: Task) : ValueTask
ValueTask(source: Sources.IValueTaskSource, token: int16) : ValueTask

--------------------
ValueTask ()
ValueTask(result: 'TResult) : ValueTask<'TResult>
ValueTask(task: Task<'TResult>) : ValueTask<'TResult>
ValueTask(source: Sources.IValueTaskSource<'TResult>, token: int16) : ValueTask<'TResult>
val z : int
Raw view Test code New version

More information

Link:http://fssnip.net/7Zn
Posted:4 years ago
Author:Eirik Tsarpalis
Tags: async , c#