要异步复制文件,是否会像这样工作?F#异步文件复制
let filecopyasync (source, target) =
let task = Task.Run((fun() ->File.Copy(source, target, true)))
// do other stuff
Async.AwaitIAsyncResult task
特别是,这将启动一个新的线程来做副本,而我“做其他的东西”?
UPDATE:
发现了另一种解决方案:
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
看起来不错!下一个问题:我可以确定线程池在任何给定时间有多大?我想限制我的线程使用,以避免压倒系统。例如如果我复制了很多文件,而且有些文件很大。假设我只想使用5个线程(任意)。我能以某种方式发现吗? – user1443098
.NET任务使用ThreadPool - CLR将管理您的任务并将其安排在池中。如果你想限制你创建的任务的数量,这个C#答案可能会有所帮助:http://stackoverflow.com/questions/2898609/system-threading-tasks-limit-the-number-of-concurrent-tasks –