@@ -110,6 +110,14 @@ module internal Utils =
110110 elif i = 1 then return ( Choice2Of2 ( b.Result, a))
111111 else return ! failwith ( sprintf " unreachable, i = %d " i) }
112112
113+ static member internal chooseTasks2 ( a : Task < 'T >) ( b : Task ) : Async < Choice < 'T * Task , Task < 'T >>> =
114+ async {
115+ let! ct = Async.CancellationToken
116+ let i = Task.WaitAny( [| ( a :> Task );( b) |], ct)
117+ if i = 0 then return ( Choice1Of2 ( a.Result, b))
118+ elif i = 1 then return ( Choice2Of2 ( a))
119+ else return ! failwith ( sprintf " unreachable, i = %d " i) }
120+
113121 type MailboxProcessor < 'Msg > with
114122 member __.PostAndAsyncReplyTask ( f : TaskCompletionSource < 'a > -> 'Msg ) : Task < 'a > =
115123 let tcs = new TaskCompletionSource< 'a>()
@@ -131,6 +139,9 @@ module internal Utils =
131139 let chooseTask ( t : Task < 'a >) ( a : Async < 'a >) : Async < 'a > =
132140 chooseTaskAsTask t a |> Async.bind Async.awaitTaskCancellationAsError
133141
142+ let toUnit ( t : Task ) : Task < unit > =
143+ t.ContinueWith ( Func<_, _>( fun ( _ : Task ) -> ()))
144+
134145 let taskFault ( t : Task < 'a >) : Task < 'b > =
135146 t
136147 |> extend ( fun t ->
@@ -1389,6 +1400,35 @@ module AsyncSeq =
13891400 yield ! loop None timeoutMs
13901401 }
13911402
1403+ let bufferByTime ( timeMs : int ) ( source : AsyncSeq < 'T >) : AsyncSeq < 'T []> = asyncSeq {
1404+ if ( timeMs < 1 ) then invalidArg " timeMs" " must be positive"
1405+ let buf = new ResizeArray<_>()
1406+ use ie = source.GetEnumerator()
1407+ let rec loop ( next : Task < 'T option > option , waitFor : Task option ) = asyncSeq {
1408+ let! next =
1409+ match next with
1410+ | Some n -> async.Return n
1411+ | None -> ie.MoveNext () |> Async.StartChildAsTask
1412+ let waitFor =
1413+ match waitFor with
1414+ | Some w -> w
1415+ | None -> Task.Delay timeMs
1416+ let! res = Async.chooseTasks2 next waitFor
1417+ match res with
1418+ | Choice1Of2 ( Some a, waitFor) ->
1419+ buf.Add a
1420+ yield ! loop ( None, Some waitFor)
1421+ | Choice1Of2 ( None,_) ->
1422+ let arr = buf.ToArray()
1423+ if arr.Length > 0 then
1424+ yield arr
1425+ | Choice2Of2 next ->
1426+ let arr = buf.ToArray()
1427+ buf.Clear()
1428+ yield arr
1429+ yield ! loop ( Some next, None) }
1430+ yield ! loop ( None, None) }
1431+
13921432 let private mergeChoiceEnum ( ie1 : IAsyncEnumerator < 'T1 >) ( ie2 : IAsyncEnumerator < 'T2 >) : AsyncSeq < Choice < 'T1 , 'T2 >> = asyncSeq {
13931433 let! move1T = Async.StartChildAsTask ( ie1.MoveNext())
13941434 let! move2T = Async.StartChildAsTask ( ie2.MoveNext())
0 commit comments