Async.RunSynchronously<'T> (Método de F#)
Ejecuta el cálculo asincrónico y espera su resultado.
Espacio de nombres/Ruta de acceso del módulo: Microsoft.FSharp.Control
Ensamblado: FSharp.Core (en FSharp.Core.dll)
// Signature:
static member RunSynchronously : Async<'T> * ?int * ?CancellationToken -> 'T
// Usage:
Async.RunSynchronously (computation)
Async.RunSynchronously (computation, timeout = timeout, cancellationToken = cancellationToken)
Parámetros
computation
Tipo: Async<'T>Cálculo que se va a ejecutar.
timeout
Tipo: intTiempo, expresado en milisegundos, durante el cual se va a aguardar el resultado del cálculo antes de que se inicie una excepción TimeoutException. Si no se proporciona ningún valor para el tiempo de espera, se usará -1 como valor predeterminado, el cual equivale a Infinite.
cancellationToken
Tipo: CancellationTokenToken de cancelación que se va a asociar al cálculo. Si no se proporciona ninguno, se utilizará el token de cancelación predeterminado.
Valor devuelto
Resultado del cálculo.
Comentarios
Si se produce una excepción en el cálculo asincrónico, esta función volverá a iniciar una excepción. Si no se proporciona ningún token de cancelación, se usará el token de cancelación predeterminado. El parámetro del tiempo de espera se proporciona en milisegundos. Un valor de -1 equivale a Infinite.
Async.RunSynchronously no debe usarse en el subproceso principal en entornos de programación asincrónicos, por ejemplo en las aplicaciones basadas en Silverlight.
Ejemplo
El ejemplo siguiente muestra cómo usar Async.RunSynchronously para ejecutar un cálculo asincrónico creado mediante Async.Parallel, sin tiempos de espera.
let bufferData (number:int) =
[| for count in 1 .. 1000 -> byte (count % 256) |]
|> Array.permute (fun index -> index)
let writeFile fileName bufferData =
async {
use outputFile = System.IO.File.Create(fileName)
do! outputFile.AsyncWrite(bufferData)
}
Seq.init 1000 (fun num -> bufferData num)
|> Seq.mapi (fun num value -> writeFile ("file" + num.ToString() + ".dat") value)
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
El ejemplo siguiente muestra cómo usar Async.RunSynchronously con tiempos de espera.
let bufferData (number:int) =
[| for i in 1 .. 1000 -> byte (i % 256) |]
|> Array.permute (fun index -> index)
// Create a counter as a reference cell that can be modified in parallel.
let counter = ref 0
// writeFileInner writes the data to an open stream
// that represents the file. It also updates the counter.
// The counter is locked because it will be accessed by
// multiple asynchronous computations.
// The counter must be updated as soon as the
// AsyncWrite completes, in the same synchronous
// program flow. There must not be a let! or do! between
// the AsyncWrite call and the counter update.
let writeFileInner (stream:System.IO.Stream) data =
let result = stream.AsyncWrite(data)
lock counter (fun () -> counter := !counter + 1)
result
// writeFile encapsulates the asynchronous write operation.
// The do! includes both the file I/O operation and the
// counter update in order to keep those operations
// together.
let writeFile fileName bufferData =
async {
use outputFile = System.IO.File.Create(fileName)
do! writeFileInner outputFile bufferData
// Updating the counter here would not be effective.
}
let async1 = Seq.init 1000 (fun num -> bufferData num)
|> Seq.mapi (fun num value ->
writeFile ("file" + num.ToString() + ".dat") value)
|> Async.Parallel
try
Async.RunSynchronously(async1, 100) |> ignore
with
| exc -> printfn "%s" exc.Message
printfn "%d write operations completed successfully." !counter
Resultados del ejemplo
Plataformas
Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2
Información de versiones
Runtime de F#
Se admite en las versiones: 2.0, 4.0
Silverlight
Se admite en la versión: 3
Vea también
Referencia
Microsoft.FSharp.Control (Espacio de nombres de F#)
Historial de cambios
Fecha |
Historial |
Motivo |
---|---|---|
Julio de 2010 |
Se han agregado ejemplos de código. |
Mejora de la información. |