要異步複製文件,是否會像這樣工作?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 –