F#中的异步等待

Jam*_*xon 4 .net f# c#-to-f# async-await

我将本实验中的一些C#重写为F#:https://github.com/Microsoft/TechnicalCommunityContent/tree/master/IoT/Azure%20Stream%20Analytics/Session%202%20-%20Hands%20On

我正在练习6,#17 - 创建SimpleEventProcessor类型.
我想实现这个CloseAsync方法

C#

async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
    {
        Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason);
        if (reason == CloseReason.Shutdown)
        {
            await context.CheckpointAsync();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我开始是这样的:

member this.CloseAsync(context, reason) = 
    Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
    match reason with 
    | CloseReason.Shutdown -> await context.CheckpointAsync()
    | _ -> ()
Run Code Online (Sandbox Code Playgroud)

但我有两个问题:

  1. 如何在F#世界中返回等待?
  2. 如何返回NOT情况 - > C#只是忽略了这种可能性.

Tar*_*mil 7

  1. 如果值具有类型Async<'T>,则可以在没有任何关键字的情况下返回它.如果它有类型TaskTask<'T>,你可以做|> Async.AwaitTask.

  2. 你可以回来async { return () }.

所以你得到这个:

member this.CloseAsync(context, reason) = 
    Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
    match reason with 
    | CloseReason.Shutdown -> context.CheckpointAsync() |> Async.AwaitTask
    | _ -> async { return () }
Run Code Online (Sandbox Code Playgroud)

另一种可能性是将整个块放在async工作流中,并使用return!1和return2:

member this.CloseAsync(context, reason) = 
    async {
        Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
        match reason with 
        | CloseReason.Shutdown -> return! context.CheckpointAsync() |> Async.AwaitTask
        | _ -> return ()
    }
Run Code Online (Sandbox Code Playgroud)

事实上,使用异步工作流允许您放弃与()C#类似的情况:

member this.CloseAsync(context, reason) = 
    async {
        Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
        if reason = CloseReason.Shutdown then
            return! context.CheckpointAsync() |> Async.AwaitTask
    }
Run Code Online (Sandbox Code Playgroud)