3 people like it.

LazyAsync

Allows to expose an F# async value in a C#-friendly API with the semantics of Lazy<> (compute on demand and guarantee only one computation)

 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: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
69: 
70: 
71: 
72: 
73: 
74: 
75: 
76: 
77: 
78: 
79: 
80: 
81: 
82: 
83: 
84: 
85: 
86: 
87: 
88: 
89: 
90: 
91: 
92: 
93: 
94: 
95: 
96: 
97: 
98: 
99: 
module FSharp.Control

open System
open System.Threading

type ComputationResult<'a> = 
    | Success of 'a
    | Failure of exn

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module ComputationResult = 

    let fromChoice choice =
        match choice with
        | Choice1Of2 value -> Success value
        | Choice2Of2 exn -> Failure exn
    
    let map f = function
        | Success value -> Success (f value)
        | Failure exn -> Failure exn

    let combine onSuccess onFailure = function
        | Success result -> onSuccess result
        | Failure exn -> onFailure exn

type AsyncState<'a> =
    | NotStarted of Async<ComputationResult<'a>>
    | Started
    | Completed of ComputationResult<'a>

type LazyAsync<'a>(state:AsyncState<'a>) = 

    let state = ref state
    let completed = Event<_>()
    let icompleted = completed.Publish

    member __.DoWhenCompleted startIfNotRunning f =
        let continuation =      
            lock state <| fun () -> 
                match !state with
                | Completed value ->
                    Some <| fun () -> f value
                | Started ->
                    icompleted.Add f
                    None
                | NotStarted asyncValue ->
                    icompleted.Add f
                    if startIfNotRunning then
                        state := Started
                        Some <| fun () ->
                            async {
                                let! value = asyncValue
                                lock state <| fun () -> state := Completed value
                                completed.Trigger value
                            } |> Async.Start
                    else
                        None
        match continuation with
        | Some continuation -> continuation()
        | _ -> ()

    member x.GetValueAsync(onSuccess:Action<_>, onFailure:Action<_>) = 

        let synchronizationContext = SynchronizationContext.Current

        let doInOriginalThread f arg = 
            if synchronizationContext <> null then
                synchronizationContext.Post ((fun _ -> f arg), null)
            else
                f arg

        ComputationResult.combine onSuccess.Invoke onFailure.Invoke
        |> doInOriginalThread
        |> x.DoWhenCompleted true

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module LazyAsync =

    let fromAsync asyncValue = 
        let asyncValue = async {
            let! value = Async.Catch asyncValue
            return ComputationResult.fromChoice value
        }
        LazyAsync(NotStarted asyncValue)

    let fromValue value =
        LazyAsync(Completed (Success value))

    let map f (x:LazyAsync<'a>) =
        let asyncValue = async { 
            let! value = Async.FromContinuations <| fun (cont, _, _) -> cont |> x.DoWhenCompleted true
            return value |> ComputationResult.map f
        }
        LazyAsync(NotStarted asyncValue)

    let subscribe onSuccess onFailure (x:LazyAsync<'a>) =
        ComputationResult.combine onSuccess onFailure
        |> x.DoWhenCompleted false
        x
Multiple items
namespace FSharp

--------------------
namespace Microsoft.FSharp
Multiple items
module Control

from FSharp

--------------------
namespace Microsoft.FSharp.Control
namespace System
namespace System.Threading
type ComputationResult<'a> =
  | Success of 'a
  | Failure of exn

Full name: FSharp.Control.ComputationResult<_>
union case ComputationResult.Success: 'a -> ComputationResult<'a>
Multiple items
union case ComputationResult.Failure: exn -> ComputationResult<'a>

--------------------
active recognizer Failure: exn -> string option

Full name: Microsoft.FSharp.Core.Operators.( |Failure|_| )
type exn = Exception

Full name: Microsoft.FSharp.Core.exn
Multiple items
type CompilationRepresentationAttribute =
  inherit Attribute
  new : flags:CompilationRepresentationFlags -> CompilationRepresentationAttribute
  member Flags : CompilationRepresentationFlags

Full name: Microsoft.FSharp.Core.CompilationRepresentationAttribute

--------------------
new : flags:CompilationRepresentationFlags -> CompilationRepresentationAttribute
type CompilationRepresentationFlags =
  | None = 0
  | Static = 1
  | Instance = 2
  | ModuleSuffix = 4
  | UseNullAsTrueValue = 8
  | Event = 16

Full name: Microsoft.FSharp.Core.CompilationRepresentationFlags
CompilationRepresentationFlags.ModuleSuffix: CompilationRepresentationFlags = 4
val fromChoice : choice:Choice<'a,#exn> -> ComputationResult<'a>

Full name: FSharp.Control.ComputationResultModule.fromChoice
val choice : Choice<'a,#exn>
union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>
val value : 'a
union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>
Multiple items
val exn : #exn

--------------------
type exn = Exception

Full name: Microsoft.FSharp.Core.exn
union case ComputationResult.Failure: exn -> ComputationResult<'a>
val map : f:('a -> 'b) -> _arg1:ComputationResult<'a> -> ComputationResult<'b>

Full name: FSharp.Control.ComputationResultModule.map
val f : ('a -> 'b)
Multiple items
val exn : exn

--------------------
type exn = Exception

Full name: Microsoft.FSharp.Core.exn
val combine : onSuccess:('a -> 'b) -> onFailure:(exn -> 'b) -> _arg1:ComputationResult<'a> -> 'b

Full name: FSharp.Control.ComputationResultModule.combine
val onSuccess : ('a -> 'b)
val onFailure : (exn -> 'b)
val result : 'a
type AsyncState<'a> =
  | NotStarted of Async<ComputationResult<'a>>
  | Started
  | Completed of ComputationResult<'a>

Full name: FSharp.Control.AsyncState<_>
union case AsyncState.NotStarted: Async<ComputationResult<'a>> -> AsyncState<'a>
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<'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 FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken

Full name: Microsoft.FSharp.Control.Async

--------------------
type Async<'T>

Full name: Microsoft.FSharp.Control.Async<_>
Multiple items
module ComputationResult

from FSharp.Control

--------------------
type ComputationResult<'a> =
  | Success of 'a
  | Failure of exn

Full name: FSharp.Control.ComputationResult<_>
union case AsyncState.Started: AsyncState<'a>
union case AsyncState.Completed: ComputationResult<'a> -> AsyncState<'a>
Multiple items
type LazyAsync<'a> =
  new : state:AsyncState<'a> -> LazyAsync<'a>
  member DoWhenCompleted : startIfNotRunning:bool -> f:(ComputationResult<'a> -> unit) -> unit
  member GetValueAsync : onSuccess:Action<'a> * onFailure:Action<exn> -> unit

Full name: FSharp.Control.LazyAsync<_>

--------------------
new : state:AsyncState<'a> -> LazyAsync<'a>
val state : AsyncState<'a>
val state : AsyncState<'a> ref
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val completed : Event<ComputationResult<'a>>
Multiple items
module Event

from Microsoft.FSharp.Control

--------------------
type Event<'T> =
  new : unit -> Event<'T>
  member Trigger : arg:'T -> unit
  member Publish : IEvent<'T>

Full name: Microsoft.FSharp.Control.Event<_>

--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate)> =
  new : unit -> Event<'Delegate,'Args>
  member Trigger : sender:obj * args:'Args -> unit
  member Publish : IEvent<'Delegate,'Args>

Full name: Microsoft.FSharp.Control.Event<_,_>

--------------------
new : unit -> Event<'T>

--------------------
new : unit -> Event<'Delegate,'Args>
val icompleted : IEvent<ComputationResult<'a>>
property Event.Publish: IEvent<ComputationResult<'a>>
member LazyAsync.DoWhenCompleted : startIfNotRunning:bool -> f:(ComputationResult<'a> -> unit) -> unit

Full name: FSharp.Control.LazyAsync`1.DoWhenCompleted
val startIfNotRunning : bool
val f : (ComputationResult<'a> -> unit)
val continuation : (unit -> unit) option
val lock : lockObject:'Lock -> action:(unit -> 'T) -> 'T (requires reference type)

Full name: Microsoft.FSharp.Core.Operators.lock
val value : ComputationResult<'a>
union case Option.Some: Value: 'T -> Option<'T>
member IObservable.Add : callback:('T -> unit) -> unit
union case Option.None: Option<'T>
val asyncValue : Async<ComputationResult<'a>>
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
member Event.Trigger : arg:'T -> unit
static member Async.Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
val continuation : (unit -> unit)
val x : LazyAsync<'a>
member LazyAsync.GetValueAsync : onSuccess:Action<'a> * onFailure:Action<exn> -> unit

Full name: FSharp.Control.LazyAsync`1.GetValueAsync
val onSuccess : Action<'a>
Multiple items
type Action =
  delegate of unit -> unit

Full name: System.Action

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

Full name: System.Action<_>

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

Full name: System.Action<_,_>

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

Full name: System.Action<_,_,_>

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

Full name: System.Action<_,_,_,_>

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

Full name: System.Action<_,_,_,_,_>

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

Full name: System.Action<_,_,_,_,_,_>

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

Full name: System.Action<_,_,_,_,_,_,_>

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

Full name: System.Action<_,_,_,_,_,_,_,_>

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

Full name: System.Action<_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_,_,_,_,_,_>

--------------------
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

Full name: System.Action<_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_>
val onFailure : Action<exn>
val synchronizationContext : SynchronizationContext
Multiple items
type SynchronizationContext =
  new : unit -> SynchronizationContext
  member CreateCopy : unit -> SynchronizationContext
  member IsWaitNotificationRequired : unit -> bool
  member OperationCompleted : unit -> unit
  member OperationStarted : unit -> unit
  member Post : d:SendOrPostCallback * state:obj -> unit
  member Send : d:SendOrPostCallback * state:obj -> unit
  member Wait : waitHandles:nativeint[] * waitAll:bool * millisecondsTimeout:int -> int
  static member Current : SynchronizationContext
  static member SetSynchronizationContext : syncContext:SynchronizationContext -> unit

Full name: System.Threading.SynchronizationContext

--------------------
SynchronizationContext() : unit
property SynchronizationContext.Current: SynchronizationContext
val doInOriginalThread : (('b -> unit) -> 'b -> unit)
val f : ('b -> unit)
val arg : 'b
SynchronizationContext.Post(d: SendOrPostCallback, state: obj) : unit
Action.Invoke(obj: 'a) : unit
Action.Invoke(obj: exn) : unit
member LazyAsync.DoWhenCompleted : startIfNotRunning:bool -> f:(ComputationResult<'a> -> unit) -> unit
Multiple items
module LazyAsync

from FSharp.Control

--------------------
type LazyAsync<'a> =
  new : state:AsyncState<'a> -> LazyAsync<'a>
  member DoWhenCompleted : startIfNotRunning:bool -> f:(ComputationResult<'a> -> unit) -> unit
  member GetValueAsync : onSuccess:Action<'a> * onFailure:Action<exn> -> unit

Full name: FSharp.Control.LazyAsync<_>

--------------------
new : state:AsyncState<'a> -> LazyAsync<'a>
val fromAsync : asyncValue:Async<'a> -> LazyAsync<'a>

Full name: FSharp.Control.LazyAsyncModule.fromAsync
val asyncValue : Async<'a>
val value : Choice<'a,exn>
static member Async.Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
val fromValue : value:'a -> LazyAsync<'a>

Full name: FSharp.Control.LazyAsyncModule.fromValue
val map : f:('a -> 'a0) -> x:LazyAsync<'a> -> LazyAsync<'a0>

Full name: FSharp.Control.LazyAsyncModule.map
val f : ('a -> 'a0)
static member Async.FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
val cont : (ComputationResult<'a> -> unit)
val subscribe : onSuccess:('a -> unit) -> onFailure:(exn -> unit) -> x:LazyAsync<'a> -> LazyAsync<'a>

Full name: FSharp.Control.LazyAsyncModule.subscribe
val onSuccess : ('a -> unit)
val onFailure : (exn -> unit)

More information

Link:http://fssnip.net/h8
Posted:4 years ago
Author:Gustavo Guerra
Tags: async , lazy