0

私は非同期ワークフローに少し慣れていて、それは私があまりよく理解していない何かを持っていると思います...私は本実世界の関数型プログラミングに従っていて、その中で非同期プリミティブをこのように書いています

let Sleep(time) =
  Async.FromContinuations(fun (cont, econt, ccont) ->
     let tmr = new System.Timers.Timer(time, AutoReset = false)
     tmr.Elapsed.Add(fun _ -> cont())
    tmr.Start()
  );;

非常に遅い階乗の実装を使用して独自の非同期プリミティブを作成しようとしましたが、コードは次のとおりです。

let rec factorial(n : int) (mem : bigint) =
   match n with
   | 0 | 1 -> printfn "%A" mem
   | _ ->  factorial (n - 1) (mem * bigint(n))


let BigFactorial(numero,mesaje)=
    Async.FromContinuations(fun (cont,error,cancelation) ->
                                printfn "begin number: %s" mesaje
                                factorial numero 1I |>ignore
                                printfn "End number: %s ." mesaje
                                cont())

今私はこれを書いた

 Async.RunSynchronously(async{
     printfn "Start!!..."
     do! BigFactorial(30000,"30M")
     do! BigFactorial(10000, "10M")
     printfn "End!!..."
 })

しかし、それは正確に非同期で実行されていません...。

Start!!...
begin number: 30M
2759537246219...(A nice long number!)
end number: 30M .
begin number: 10M .
2846259680917054518906...(other nice number)
End!!...

並行して実行するとうまくいきます...

let task1 = async{
   printfn "begin"
   do! BigFactorial(30000,"30")
   printfn "end..." 
}

let task2 = async{
   printfn "begin"
   do! BigFactorial(10000,"10")
   printfn "end!!..." 
}


Async.RunSynchronously(Async.Parallel[task1;task2])

begin
begin: 30 
begin
begin: 10M

//long numbers here

end....
end.....

しかし、最初のコードが機能しない理由(またはいくつかの理由!)を知りたいのですが...助けてくれてありがとう...

4

1 に答える 1

2

すべての asyncバインディングと同様do!に、現在のスレッドで実行されるため、2 つdo!のシーケンシャル が順番に実行されます。

それらを並行して実行する場合は、明示的に指定する必要があります。

async {
   printfn "Start!!..."
   let! tokenA = BigFactorial (30000, "30M") |> Async.StartChild // on new thread
   let! tokenB = BigFactorial (10000, "10M") |> Async.StartChild // on new thread
   do! tokenA // block until `BigFactorial (30000, "30M")` finishes
   do! tokenB // block until `BigFactorial (10000, "10M")` finishes
   printfn "End!!..." }
|> Async.RunSynchronously
于 2012-06-15T01:28:11.683 に答える