Async await in F #
I am rewriting some of the C # in this lab in F #: https://github.com/Microsoft/TechnicalCommunityContent/tree/master/IoT/Azure%20Stream%20Analytics/Session%202%20-%20Hands%20On
I'm in Exercise 6, # 17 - creating a type SimpleEventProcessor
.
I want to implement a methodCloseAsync
FROM#
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();
}
}
and I started like this:
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()
| _ -> ()
but I have 2 questions:
- How do I get back to the F # world?
- How do I return the NOT case -> C # just ignore this possibility.
source to share
-
If the type is of value
Async<'T>
, you can simply return it without any keyword. If it is of typeTask
orTask<'T>
, you can do|> Async.AwaitTask
. -
You can return
async { return () }
.
So you get this:
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 () }
Another possibility is to put the whole block in a workflow async
and use return!
for 1 and return
2:
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 ()
}
In fact, using an asynchronous workflow avoids a case ()
similar to 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
}
source to share