3 people like it.

Async.TryFinally and an application

F# computation expressions do not allow monadic expressions inside `finally` clauses. If we allow ourselves a bit of ugliness this can be circumvented by using a combinator. Here's an implementation for asynchronous workflows and a small application.

Async.TryFinally Implementation

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
type Async with
    static member TryFinally(body : Async<'T>, finallyF : Async<unit>) = async {
        let! ct = Async.CancellationToken
        return! Async.FromContinuations(fun (sc,ec,cc) ->
            let sc' (t : 'T) = Async.StartWithContinuations(finallyF, (fun () -> sc t), ec, cc, ct)
            let ec' (e : exn) = Async.StartWithContinuations(finallyF, (fun () -> ec e), ec, cc, ct)
            Async.StartWithContinuations(body, sc', ec', cc, ct))
    }

Simple Examples

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
let test fail wf = 
    Async.TryFinally(wf, async { if fail then failwith "boom" else printfn "42"}) 
    |> Async.RunSynchronously

test false (async { return 42}) // side effect
test true (async { return 42}) // side effect & "boom"
test false (async { return do failwith "kaboom" }) // side effect & "kaboom"
test true (async { return do failwith "kaboom" }) // side effect & "boom"

Application: IAsyncDisposable

1: 
2: 
3: 
4: 
5: 
6: 
type IAsyncDisposable =
    abstract Dispose : unit -> Async<unit>

type AsyncBuilder with
    member __.Using<'T, 'U when 'T :> IAsyncDisposable>(value : 'T, bindF : 'T -> Async<'U>) : Async<'U> =
        Async.TryFinally(async { return! bindF value }, async { return! value.Dispose() })

IAsyncDisposable Example

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
let mkDummyDisposable () = 
    { new IAsyncDisposable with 
        member __.Dispose () = async { printfn "Disposed" }}

async {
    use d = mkDummyDisposable ()
    return d.GetHashCode()
} |> Async.RunSynchronously

async {
    use d = mkDummyDisposable ()
    return null.GetHashCode()
} |> Async.RunSynchronously
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<_>
static member Async.TryFinally : body:Async<'T> * finallyF:Async<unit> -> Async<'T>

Full name: Script.TryFinally
val body : Async<'T>
val finallyF : Async<unit>
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val ct : System.Threading.CancellationToken
property Async.CancellationToken: Async<System.Threading.CancellationToken>
static member Async.FromContinuations : callback:(('T -> unit) * (exn -> unit) * (System.OperationCanceledException -> unit) -> unit) -> Async<'T>
val sc : ('T -> unit)
val ec : (exn -> unit)
val cc : (System.OperationCanceledException -> unit)
val sc' : ('T -> unit)
val t : 'T
static member Async.StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(System.OperationCanceledException -> unit) * ?cancellationToken:System.Threading.CancellationToken -> unit
val ec' : (exn -> unit)
val e : exn
type exn = System.Exception

Full name: Microsoft.FSharp.Core.exn
val test : fail:bool -> wf:Async<'a> -> 'a

Full name: Script.test
val fail : bool
val wf : Async<'a>
static member Async.TryFinally : body:Async<'T> * finallyF:Async<unit> -> Async<'T>
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
static member Async.RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:System.Threading.CancellationToken -> 'T
type IAsyncDisposable =
  interface
    abstract member Dispose : unit -> Async<unit>
  end

Full name: Script.IAsyncDisposable
abstract member IAsyncDisposable.Dispose : unit -> Async<unit>

Full name: Script.IAsyncDisposable.Dispose
type AsyncBuilder =
  private new : unit -> AsyncBuilder
  member Bind : computation:Async<'T> * binder:('T -> Async<'U>) -> Async<'U>
  member Combine : computation1:Async<unit> * computation2:Async<'T> -> Async<'T>
  member Delay : generator:(unit -> Async<'T>) -> Async<'T>
  member For : sequence:seq<'T> * body:('T -> Async<unit>) -> Async<unit>
  member Return : value:'T -> Async<'T>
  member ReturnFrom : computation:Async<'T> -> Async<'T>
  member TryFinally : computation:Async<'T> * compensation:(unit -> unit) -> Async<'T>
  member TryWith : computation:Async<'T> * catchHandler:(exn -> Async<'T>) -> Async<'T>
  member Using : resource:'T * binder:('T -> Async<'U>) -> Async<'U> (requires 'T :> IDisposable)
  ...

Full name: Microsoft.FSharp.Control.AsyncBuilder
member AsyncBuilder.Using : value:'T * bindF:('T -> Async<'U>) -> Async<'U> (requires 'T :> IAsyncDisposable)

Full name: Script.Using
val value : #IAsyncDisposable
val bindF : (#IAsyncDisposable -> Async<'U>)
abstract member IAsyncDisposable.Dispose : unit -> Async<unit>
val mkDummyDisposable : unit -> IAsyncDisposable

Full name: Script.mkDummyDisposable
val d : IAsyncDisposable
System.Object.GetHashCode() : int
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/r4
Posted:9 years ago
Author:Eirik Tsarpalis
Tags: async , try finally