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)
但我有两个问题:
如果值具有类型Async<'T>,则可以在没有任何关键字的情况下返回它.如果它有类型Task或Task<'T>,你可以做|> Async.AwaitTask.
你可以回来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)
| 归档时间: |
|
| 查看次数: |
591 次 |
| 最近记录: |