Async.SwitchToNewThread 方法 (F#)
建立非同步計算,這個計算會建立新執行緒並在該執行緒中執行其接續。
**命名空間/模組路徑:**Microsoft.FSharp.Control
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
static member SwitchToNewThread : unit -> Async<unit>
// Usage:
Async.SwitchToNewThread ()
傳回值
將在新執行緒上執行的計算作業。
範例
下列程式碼範例示範如何使用 Async.SwitchToNewThread 和 Async.SwitchToThreadPool,將同步方法呼叫包裝為非同步方法。
open System
open System.IO
let asyncMethod f =
async {
do! Async.SwitchToNewThread()
let result = f()
do! Async.SwitchToThreadPool()
return result
}
let GetFilesAsync(path) = asyncMethod (fun () -> Directory.GetFiles(path))
let listFiles path =
async {
let! files = GetFilesAsync(path)
Array.iter (fun elem -> printfn "%s" elem) files
}
printfn "Here we go..."
// The output is interleaved, which shows that these are both
// running simultaneously.
Async.Start(listFiles ".")
Async.Start(listFiles ".")
Console.WriteLine("Press a key to continue...")
Console.ReadLine() |> ignore
平台
Windows 8 中, Windows 7, Windows Server 2012 上, Windows Server 2008 R2
版本資訊
F# 核心程式庫版本
支援版本:2.0, 4.0,可攜式執行檔 (PE)。