I have an F# program to copy files that I want to work asynchronously. So far I have:
let asyncFileCopy (source, target, overwrite) =
let copyfn (source,target,overwrite) =
printfn "Copying %s to %s" source target
File.Copy(source, target, overwrite)
printfn "Copyied %s to %s" source target
let fn = new Func<string * string * bool, unit>(copyfn)
Async.FromBeginEnd((source, target, overwrite), fn.BeginInvoke, fn.EndInvoke)
[<EntryPoint>]
let main argv =
let copyfile1 = asyncFileCopy("file1", "file2", true)
let copyfile2 = asyncFileCopy("file3", "file4", true)
let asynctask =
[copyfile1; copyfile2]
|> Async.Parallel
printfn "doing other stuff"
Async.RunSynchronously asynctask |> ignore
which works (the files are copied) but not in the way I want. I want to start the parallel copy operations so that they begin copying. Meanwhile, I want to continue doing stuff on the main thread. Later, I want to wait for the asynchronous tasks to complete. What my code seems to do is set up the parallel copies, then do other stuff, but not actually execute the copies until it hits Async.Runsychronously.
Is there a way to, in effect, Async.Run"a"synchronously, to get the copies started in the thread pool, then do other stuff and later wait for the copies to finish?
1 Answer 1
Figured it out:
let asynctask =
[copyfile1; copyfile2]
|> Async.Parallel
|> Async.StartAsTask
let result = Async.AwaitIAsyncResult asynctask
printfn "doing other stuff"
Async.RunSynchronously result |> ignore
printfn "Done"
The key is using StartAsTask, AwaitIAsyncResult and only later RunSynchronously to await task completion