Partager via


Async.SwitchToNewThread, méthode (F#)

Crée un calcul asynchrone qui crée un nouveau thread et exécute sa continuation dans ce thread.

Espace de noms/Chemin du module : Microsoft.FSharp.Control

Assembly : FSharp.Core (in FSharp.Core.dll)

// Signature:
static member SwitchToNewThread : unit -> Async<unit>

// Usage:
Async.SwitchToNewThread ()

Valeur de retour

Calcul qui s'exécutera sur un nouveau thread.

Exemple

L'exemple de code suivant montre comment utiliser Async.SwitchToNewThread et Async.SwitchToThreadPool pour encapsuler un appel de méthode synchrone en tant que méthode asynchrone.

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

Plateformes

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Informations de version

Runtime F#

Pris en charge dans : 2.0, 4.0

Silverlight

Prise en charge dans : 3

Voir aussi

Référence

Control.Async, classe (F#)

Microsoft.FSharp.Control, espace de noms (F#)

Historique des modifications

Date

Historique

Motif

Juillet 2010

Ajout d'un exemple de code

Améliorations apportées aux informations.