我有一个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”,在线程池中启动拷贝,然后做其他事情,然后等待拷贝完成?
发布于 2017-04-06 03:12:02
弄清楚了:
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来等待任务完成
https://stackoverflow.com/questions/43239247
复制相似问题