2

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?

asked Apr 5, 2017 at 18:45

1 Answer 1

3

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

answered Apr 5, 2017 at 19:12
Sign up to request clarification or add additional context in comments.

1 Comment

Once 48 hours have passed since you asked your question, you'll be able to accept your own answer by clicking the checkbox under its score. (The system requires you to wait 48 hours because other people might also answer it, with answers that turn out to be even better than yours.) Once you're able to accept your own answer, you should do so, since that gives it a different color in search results and lets other people know that if they click on this question, they will see an answer that solved the question. (Something very nice to know when you're searching for the answer yourself!)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.