这里有很多很好的答案,但我认为我对这个问题采取了不同的角度:F#的异步真的如何工作?
与C#F#中的async/await
不同,开发人员实际上可以实现自己的版本Async
。这可以是了解Async
如何工作的好方法。
(对于感兴趣的源代码Async
可以在这里找到:https://github.com/Microsoft/visualfsharp/blob/fsharp4/src/fsharp/FSharp.Core/control.fs)
由于我们的基本构建模块为我们的DIY工作流程,我们定义:
type DIY<'T> = ('T->unit)->unit
这是接受另一个函数函数(称为继续),在'T
类型的结果准备就绪时调用。这允许DIY<'T>
在不阻塞调用线程的情况下启动后台任务。当结果准备好时,继续被调用,允许计算继续。
该F#Async
构建块有点复杂,因为它还包括取消和异常延续,但本质上就是这样。
为了支持F#工作流语法,我们需要定义一个计算表达式(https://msdn.microsoft.com/en-us/library/dd233182.aspx)。虽然这是一个相当先进的F#功能,但它也是F#最令人惊喜的功能之一。定义的两个最重要的操作是return
& bind
,F#使用它们将我们的DIY<_>
构造块组合到聚合的DIY<_>
构件中。
adaptTask
用于将Task<'T>
修改为DIY<'T>
。 startChild
允许启动几个simulatenous DIY<'T>
,请注意,它不启动新线程为了这样做,但重新使用调用线程。
没有这里的任何进一步的ADO的示例程序:
open System
open System.Diagnostics
open System.Threading
open System.Threading.Tasks
// Our Do It Yourself Async workflow is a function accepting a continuation ('T->unit).
// The continuation is called when the result of the workflow is ready.
// This may happen immediately or after awhile, the important thing is that
// we don't block the calling thread which may then continue executing useful code.
type DIY<'T> = ('T->unit)->unit
// In order to support let!, do! and so on we implement a computation expression.
// The two most important operations are returnValue/bind but delay is also generally
// good to implement.
module DIY =
// returnValue is called when devs uses return x in a workflow.
// returnValue passed v immediately to the continuation.
let returnValue (v : 'T) : DIY<'T> =
fun a ->
a v
// bind is called when devs uses let!/do! x in a workflow
// bind binds two DIY workflows together
let bind (t : DIY<'T>) (fu : 'T->DIY<'U>) : DIY<'U> =
fun a ->
let aa tv =
let u = fu tv
u a
t aa
let delay (ft : unit->DIY<'T>) : DIY<'T> =
fun a ->
let t = ft()
t a
// starts a DIY workflow as a subflow
// The way it works is that the workflow is executed
// which may be a delayed operation. But startChild
// should always complete immediately so in order to
// have something to return it returns a DIY workflow
// postProcess checks if the child has computed a value
// ie rv has some value and if we have computation ready
// to receive the value (rca has some value).
// If this is true invoke ca with v
let startChild (t : DIY<'T>) : DIY<DIY<'T>> =
fun a ->
let l = obj()
let rv = ref None
let rca = ref None
let postProcess() =
match !rv, !rca with
| Some v, Some ca ->
ca v
rv := None
rca := None
| _ , _ ->()
let receiver v =
lock l <| fun() ->
rv := Some v
postProcess()
t receiver
let child : DIY<'T> =
fun ca ->
lock l <| fun() ->
rca := Some ca
postProcess()
a child
let runWithContinuation (t : DIY<'T>) (f : 'T -> unit) : unit =
t f
// Adapts a task as a DIY workflow
let adaptTask (t : Task<'T>) : DIY<'T> =
fun a ->
let action = Action<Task<'T>> (fun t -> a t.Result)
ignore <| t.ContinueWith action
// Because C# generics doesn't allow Task<void> we need to have
// a special overload of for the unit Task.
let adaptUnitTask (t : Task) : DIY<unit> =
fun a ->
let action = Action<Task> (fun t -> a())
ignore <| t.ContinueWith action
type DIYBuilder() =
member x.Return(v) = returnValue v
member x.Bind(t,fu) = bind t fu
member x.Delay(ft) = delay ft
let diy = DIY.DIYBuilder()
open DIY
[<EntryPoint>]
let main argv =
let delay (ms : int) = adaptUnitTask <| Task.Delay ms
let delayedValue ms v =
diy {
do! delay ms
return v
}
let complete =
diy {
let sw = Stopwatch()
sw.Start()
// Since we are executing these tasks concurrently
// the time this takes should be roughly 700ms
let! cd1 = startChild <| delayedValue 100 1
let! cd2 = startChild <| delayedValue 300 2
let! cd3 = startChild <| delayedValue 700 3
let! d1 = cd1
let! d2 = cd2
let! d3 = cd3
sw.Stop()
return sw.ElapsedMilliseconds,d1,d2,d3
}
printfn "Starting workflow"
runWithContinuation complete (printfn "Result is: %A")
printfn "Waiting for key"
ignore <| Console.ReadKey()
0
程序的输出应该是这样的:
Starting workflow
Waiting for key
Result is: (706L, 1, 2, 3)
当运行程序说明Waiting for key
被immidiately打印为控制台线程不会阻止启动工作流程。大约700ms后打印结果。
我希望这有趣的是,一些F#开发者
http://stackoverflow.com/questions/2444676/understanding-f-asynchronous-programming – 2010-09-07 17:17:58