Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module AsyncPeriodicWork =
- let createCanceller () =
- new System.Threading.CancellationTokenSource()
- let start (canceller:System.Threading.CancellationTokenSource) (intervalMillis:int) (work:(unit->unit)) (onFault:(System.Exception->unit) option)=
- let loop = async {
- printfn "starting..."
- try
- while true do
- work()
- do! Async.Sleep intervalMillis
- with
- | ex -> match onFault with
- | Some(handler) -> ex |> handler
- | None -> ()
- printfn "exiting"
- }
- Async.Start (loop, canceller.Token)
- let startCancellable (intervalMillis:int) (work:(unit->unit)) (onFault:(System.Exception->unit) option) =
- let canceller = createCanceller()
- start canceller intervalMillis work onFault
- canceller
- module examples =
- let run1 () =
- let printTimestamp x =
- fun () -> printfn "%s %A" x System.DateTime.Now
- let cts = AsyncPeriodicWork.createCanceller()
- AsyncPeriodicWork.start cts 500 (printTimestamp "A") None
- AsyncPeriodicWork.start cts 100 (printTimestamp "B") None
- //System.Threading.Thread.Sleep(2000)
- //cts.Cancel()
- cts
- let run2 () =
- let stopwatch = System.Diagnostics.Stopwatch()
- stopwatch.Start()
- let cts = AsyncPeriodicWork.startCancellable 100 (fun () -> printfn "%A" stopwatch.ElapsedMilliseconds) None
- //System.Threading.Thread.Sleep(1000)
- //cts.Cancel()
- cts
- let run3 () =
- let work = fun () ->
- match System.Random().Next() % 10 with
- | x when x < 8 -> printfn "random is %A" x
- | _ -> failwith "foobar"
- let cts = AsyncPeriodicWork.startCancellable 100 work (Some(fun ex -> printfn "%A!" ex.Message))
- cts
- let cancelAfterMillis (millis:int) (cts:System.Threading.CancellationTokenSource) =
- System.Threading.Thread.Sleep(millis)
- cts.Cancel()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement