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,可攜式執行檔 (PE)。