I want to read data as it's appearing in a file (the data is written by another process). Something like "continuous reading".
Simple code that just read a file to the end and finishes works without problems:
let readStream (r: StreamReader) =
seq {
while not r.EndOfStream do
yield r.ReadLine() }
Now I add the following logic to it: if it reaches the end of the stream, it waits for a second, then tries again. If the data has not appeared, it sleeps for 2 seconds and so on up to 5 seconds in 5 attempts:
let readStream (r: StreamReader) =
let rec loop waitTimeout waits =
seq {
match waitTimeout with
| None ->
if not r.EndOfStream then
yield r.ReadLine()
yield! loop None 0
else yield! loop (Some 1000) waits
| Some timeout when waits < 5 ->
let waits = waits + 1
printfn "Sleeping for %d ms (attempt %d)..." timeout waits
Thread.Sleep (timeout * waits)
yield! loop None waits
| _ -> ()
}
loop None 0
Unfortunately, it turns out to be not-tail recursive and the app crashes with StackOverflow exception quickly.
Can anybody help with this?