要异步复制文件,这样的代码是否可行?
let filecopyasync (source, target) =
let task = Task.Run((fun () ->File.Copy(source, target, true)))
// do other stuff
Async.AwaitIAsyncResult task
特别是,这会启动一个新的线程来执行复制操作,同时我可以“干其他事情”吗?
更新:
找到另一种解决方案:
let asyncFileCopy (source, target, overwrite) =
printfn "Copying %s to %s" source target
let fn = new Func<string * string * bool, unit>(File.Copy)
Async.FromBeginEnd((source, target, overwrite), fn.BeginInvoke, fn.EndInvoke)
let copyfile1 = asyncFileCopy("file1", "file2", true)
let copyfile2 = asyncFileCopy("file3", "file4", true)
[copyfile1; copyfile2] |> seq |> Async.Parallel |> Async.RunSynchronously |> ignore
FileOptions.Asynchronous
标志创建流,CopyToAsync
方法是否会执行异步复制呢?请参考例如https://dev59.com/sHNA5IYBdhLWcg3wpfiu#35467471。 - kvb