共用方式為


Async.SwitchToNewThread 方法 (F#)

更新:2010 年 7 月

建立非同步計算,這個計算會建立新執行緒並在該執行緒中執行其接續。

命名空間/模組路徑: 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 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2

版本資訊

F# 執行階段

支援版本:2.0、4.0

Silverlight

支援版本:3

請參閱

參考

Control.Async 類別 (F#)

Microsoft.FSharp.Control 命名空間 (F#)

變更記錄

日期

History

原因

2010 年 7 月

加入程式碼範例。

資訊加強。