Async.RunSynchronously<'T> 方法 (F#)
运行异步计算并等待其结果。
命名空间/模块路径: Microsoft.FSharp.Control
程序集:FSharp.Core(在 FSharp.Core.dll 中)
// Signature:
static member RunSynchronously : Async<'T> * ?int * ?CancellationToken -> 'T
// Usage:
Async.RunSynchronously (computation)
Async.RunSynchronously (computation, timeout = timeout, cancellationToken = cancellationToken)
参数
computation
类型:Async<'T>要运行的计算。
timeout
类型:int引发 TimeoutException 之前需等待计算结果的时间量(以毫秒为单位)。 如果未提供超时值,则使用默认值 -1,使之与 Infinite 相对应。
cancellationToken
类型:CancellationToken要与计算相关联的取消标记。 如果未提供取消标记,则使用默认取消标记。
返回值
计算的结果。
备注
如果异步计算中发生异常,则此函数将重新引发异常。 如果未提供取消标记,则使用默认取消标记。 超时参数以毫秒为单位给出。 值 -1 等效于 Infinite。
在主线程不应使用Async.RunSynchronously 在异步程序环境,例如基于的应用程序。
示例
以下示例演示如何使用 Async.RunSynchronously 在不超时运行用 Async.Parallel 创建的异步计算。
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
以下示例演示如何在超时时使用 Async.RunSynchronously。
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
示例输出
平台
Windows 8,Windows 7,Windows server 2012中,Windows server 2008 R2
版本信息
F#核心库版本
支持:2.0,4.0,可移植