F#ASync.Parallel加主线程

时间:2017-04-05 18:45:06

标签: asynchronous f#

我有一个F#程序来复制我想要异步工作的文件。到目前为止,我有:

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

哪个有效(文件被复制)但不是我想要的方式。我想启动并行复制操作,以便它们开始复制。同时,我想继续在主线程上做一些事情。后来,我想等待异步任务完成。我的代码似乎做的是设置并行副本,然后执行其他操作,但实际上不执行副本,直到它遇到Async.Runsychronously。

实际上是否有一种方法可以同步Async.Run“a”,以便在线程池中启动副本,然后执行其他操作,然后等待副本完成?

1 个答案:

答案 0 :(得分:2)

想出来:

 let asynctask =
    [copyfile1; copyfile2] 
    |> Async.Parallel 
    |> Async.StartAsTask

let result = Async.AwaitIAsyncResult asynctask

printfn "doing other stuff"

Async.RunSynchronously result |> ignore
printfn "Done"

关键是使用StartAsTask,AwaitIAsyncResult,以后只有RunSynchronously才能等待任务完成