MailboxProcessor.Scan<'Msg,'T>-Methode (F#)
Sucht nach einer Meldung, indem die Meldungen in der Reihenfolge ihres Eintreffens geprüft werden, bis eine angegebene Funktion einen Some-Wert zurückgibt. Andere Meldungen verbleiben in der Warteschlange.
Namespace/Modulpfad: Microsoft.FSharp.Control
Assembly: FSharp.Core (in FSharp.Core.dll)
// Signature:
member this.Scan : ('Msg -> Async<'T> option) * ?int -> Async<'T>
// Usage:
mailboxProcessor.Scan (scanner)
mailboxProcessor.Scan (scanner, timeout = timeout)
Parameter
scanner
Typ: 'Msg -> Async<'T> optionEine Funktion zur Rückgabe von None, wenn die Meldung übersprungen werden soll, oder Some, wenn die Meldung verarbeitet und aus der Warteschlange entfernt werden soll.
timeout
Typ: intEin optionales Timeout in Millisekunden. Wird standardmäßig auf -1 festgelegt, was Infinite entspricht.
Ausnahmen
Ausnahme |
Bedingung |
---|---|
Wird ausgelöst, wenn das Timeout überschritten wird. |
Rückgabewert
Eine asynchrone Berechnung (Async-Objekt), die vom scanner aus der gelesenen Meldung erstellt wurde.
Hinweise
Diese Methode ist für die Verwendung im Coderumpf des Agents vorgesehen. Für jeden Agent darf maximal ein Reader gleichzeitig aktiv sein. Es darf also nur maximal ein Aufruf von Receive, TryReceive, Scan oder TryScan aktiv sein. Der Text der scanner-Funktion wird während seiner Ausführung gesperrt, die Sperre wird jedoch vor der Ausführung des asynchronen Workflows aufgehoben.
Beispiel
Im folgenden Beispiel wird die Verwendung der Scan-Methode gezeigt. In diesem Code verwalten Postfachprozessor-Agents eine Reihe von simulierten Aufträgen, die ausgeführt werden und ein Ergebnis berechnen.
open System
open System.Threading
let random = System.Random()
// Generates mock jobs by using Async.Sleep.
let createJob(id:int, source:CancellationTokenSource) =
let job = async {
// Let the time be a random number between 1 and 10000.
// The mock computed result is a floating point value.
let time = random.Next(10000)
let result = random.NextDouble()
let count = ref 1
while (!count <= 100 && not source.IsCancellationRequested) do
do! Async.Sleep(time / 100)
count := !count + 1
return result
}
id, job, source
type Result = double
// A Job consists of a job ID and a computation that produces a single result.
type Job = int * Async<Result> * CancellationTokenSource
type Message = int * Result
let context = System.Threading.SynchronizationContext.Current
// This agent processes when jobs are completed.
let completeAgent = MailboxProcessor<Message>.Start(fun inbox ->
let rec loop n =
async {
let! (id, result) = inbox.Receive()
printfn "The result of job #%d is %f" id result
do! loop (n + 1)
}
loop (0))
// inprogressAgent maintains a queue of in-progress jobs that can be
// scanned to remove canceled jobs. It never runs its processor function,
// so we set it to do nothing.
let inprogressAgent = new MailboxProcessor<Job>(fun _ -> async { () })
// This agent starts each job in the order in which it is received.
let runAgent = MailboxProcessor<Job>.Start(fun inbox ->
let rec loop n =
async {
let! (id, job, source) = inbox.Receive()
printfn "Starting job #%d" id
// Post to the in-progress queue.
inprogressAgent.Post(id, job, source)
// Start the job.
Async.StartWithContinuations(job,
(fun result -> completeAgent.Post(id, result)),
(fun _ -> ()),
(fun cancelException -> printfn "Canceled job #%d" id),
source.Token)
do! loop (n + 1)
}
loop (0))
for id in 1 .. 10 do
let source = new CancellationTokenSource()
runAgent.Post(createJob(id, source))
let cancelJob(cancelId) =
Async.RunSynchronously(
inprogressAgent.Scan(fun (jobId, result, source) ->
let action =
async {
printfn "Canceling job #%d" cancelId
source.Cancel()
}
// Return Some(async) if the job ID matches.
if (jobId = cancelId) then
Some(action)
else
None))
printfn "Specify a job by number to cancel it, then press Enter."
let mutable finished = false
while not finished do
let input = System.Console.ReadLine()
let a = ref 0
if (Int32.TryParse(input, a) = true) then
cancelJob(!a)
else
printfn "Terminating."
finished <- true
Eine Beispielsitzung folgt.
Plattformen
Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2
Versionsinformationen
F#-Kernbibliotheksversionen
Unterstützt in: 2.0, 4.0, Portable